首页 > 解决方案 > 如何通过 JS 获取元素的定义宽度?

问题描述

我需要找出通过页面上元素的CSS 定义的宽度;我不需要浏览器计算的实际宽度!

从内联样式属性中获取宽度值是没有问题的,但是当它在 CSS 文件中时如何获取宽度定义?

这是一个包含 3 个 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>

标签: javascriptcss

解决方案


编辑

我最初的答案错过了一点:如果元素应用了内联样式,请使用它,如果没有内联样式,请查看样式表。

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>


推荐阅读