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

时间:2014-01-23 12:22:53

标签: javascript css border

我只在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>

2 个答案:

答案 0 :(得分:3)

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,但适用于所有其他现代浏览器。 (Browser Support

答案 1 :(得分:1)

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

  

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