[英]Why is DOM element border width not returned?
I've tried this in IE9 only, and I'm receiving just an empty string back - no border width. 我只在IE9中尝试过此方法,并且只收到一个空字符串-没有边框宽度。 What is wrong?! 怎么了?!
<!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>
The style
object only contains data stored in the element's HTML style
attribute. style
对象仅包含存储在元素的HTML style
属性中的数据。 Here the element has no style
attribute, let alone a border-width
declaration within. 这里的元素没有style
属性,更不用说其中的border-width
声明了。 This would only work if your markup looked like this: 仅当您的标记如下所示时,这才起作用:
<div class="myCanvas" style="border-width:2px">Something here</div>
2px 2像素
To pull computed CSS styles, you need to use window.getComputedStyle()
: 要提取计算的CSS样式,您需要使用window.getComputedStyle()
:
var div = document.getElementsByTagName('div')[0],
borderWidth = window.getComputedStyle(div).borderWidth;
console.log(borderWidth);
2px 2像素
Unfortunately this will not work on IE8, but will work on all other modern browsers. 不幸的是,这不适用于IE8,但可以在所有其他现代浏览器上使用。 ( Browser Support ) ( 浏览器支持 )
element.style
only refers to the element's style attribute . element.style
仅指元素的style 属性 。 From MDN : 从MDN :
To get the values of all CSS properties for an element you should use
window.getComputedStyle()
instead. 要获取元素的所有CSS属性的值,应改用window.getComputedStyle()
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.