为什么未返回DOM元素边框宽度



我仅在IE9中尝试过此操作,我只收到一个空字符串 - 没有边框宽度。怎么了?!

<!DOCTYPE html><html><head>
<style type="text/css">
    .myCanvas {
        border-width: 2px;
        border-style: solid;
        border-color: red;
    }
</style>
</head><body>
    <div class="myCanvas">Something here</div>
    <script type="text/javascript">
        (function(){
            var borderWidth = document.getElementsByTagName('div')[0].style.borderWidth;
            console.log(borderWidth);
        })();
    </script>
</body>html>

style对象仅包含元素HTML style属性中存储的数据。在这里,该元素没有style属性,更不用说内部的border-width声明了。这只有在您的标记看起来像这样时才有效:

<div class="myCanvas" style="border-width:2px">Something here</div>

2px

要拉出计算的CSS样式,您需要使用window.getComputedStyle()

var div = document.getElementsByTagName('div')[0],
    borderWidth = window.getComputedStyle(div).borderWidth;
console.log(borderWidth);

2px

JSFIDDLE DEMO

不幸的是,这将在IE8上不起作用,但会在所有其他现代浏览器上使用。(浏览器支持)

element.style仅指元素的样式属性。来自MDN:

要获取所有CSS属性的值,您应该使用window.getComputedStyle()

最新更新