javascript - 如何通过 JS 获取元素的定义宽度?
问题描述
我需要找出通过页面上元素的CSS 定义的宽度;我不需要浏览器计算的实际宽度!
从内联样式属性中获取宽度值是没有问题的,但是当它在 CSS 文件中时如何获取宽度定义?
这是一个包含 3 个 div 元素的简短示例:
- 第一个 div 使用内联 CSS 宽度,我可以找到它。
- 第二个 div 具有通过 CSS 定义的相对宽度 → 如何找到“50%”值?
- 第三个 div 没有宽度定义 → 我怎样才能发现这个 div没有宽度?
var box1 = document.getElementById('item1');
var box2 = document.getElementById('item2');
var box3 = document.getElementById('item3');
console.log('Box 1 width:', box1.style.width); // all good!
console.log('Box 2 width:', box2.style.width); // required result: "50%"
console.log('Box 3 width:', box3.style.width); // required result: "", "initial" or undefined
#item1 { width: 200px; }
#item2 { width: 50%; }
#item1, #item2, #item3 { background: #ccc; margin: 2px; padding: 5px }
<div id="item1" style="width: auto">Box 1</div>
<div id="item2">Box 2</div>
<div id="item3">Box 3</div>
解决方案
编辑
我最初的答案错过了一点:如果元素应用了内联样式,请使用它,如果没有内联样式,请查看样式表。
getComputedStyle
将为您提供 div 的实际宽度,而不是样式表中指定的宽度。
如果您需要找出样式表中定义的规则,而不是元素的实际样式值,您可以通过遍历样式表来做到这一点。
let cssRules = Array.from(document.styleSheets[0].rules); //the 3 styles youve set
function getStylesheetPropertyForElement(id, property) {
let element = document.getElementById(id), appliedStyle ="";
if (!element) return false;
// prefer inline style if available!
if (element.style[property]) return element.style[property];//
// reverse the order of the rules.
// naively assumes the most recent rule is the one thats applied
// makes no attempt to handle priority and !important
cssRules.reverse().some(rule => {
// does the selector for this rule match?
if (element.matches(rule.selectorText)) {
//yes. is there a rule for the required property?
if (Array.from(rule.style).some(el=>el === property)) {
// great
appliedStyle = rule.style[property];
return true;
}
}
});
return appliedStyle;
}
console.log(getStylesheetPropertyForElement('item1', 'width')); //auto
console.log(getStylesheetPropertyForElement('item2', 'width')); //50%
console.log(getStylesheetPropertyForElement('item3', 'width')); //""
#item1 { width: 200px; }
#item2 { width: 50%; }
#item1, #item2, #item3 { background: #ccc; margin: 2px; padding: 5px }
<div id="item1" style="width: auto">Box 1</div>
<div id="item2">Box 2</div>
<div id="item3">Box 3</div>
推荐阅读
- python - 原点的主要网格线未显示在 matplotlib 中
- javascript - 在 react-native 中单击登录时如何设置状态?
- python - 使用元组元素创建 3d np 数组
- javascript - Display div with a hint only if one specific option is chosen/active. AngularJS
- python - lightgbm 的importance_type 'split' 和xgboost 中的importance_type 'weight` 一样吗?
- java - 创建 BitSet 的 toByteArray 方法(错误的字节顺序)
- javascript - 算法可以达到的最远建筑物 - JavaScript
- javascript - 你能用不同的数据处理选项重新“初始化”一个 Facebook 像素吗?
- api - API Get 请求在网络外被阻止
- sql - 给定时间内的 Postgres SUM