我只在 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
不幸的是,这不适用于 IE8,但适用于所有其他现代浏览器。 ( Browser Support )
关于javascript - 为什么不返回 DOM 元素边框宽度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21308042/