2014-01-23 40 views
1

我试过这个只在IE9中,我只收到一个空字符串 - 没有边框宽度。哪里不对?!为什么不返回DOM元素边框宽度?

<!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> 
+4

你正在看的是style属性设置的style属性,你需要看的是计算的样式。 – Musa

回答

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

+0

对于IE 8及更高版本,如果您需要/决定支持它们,则需要其他东西。 –

+0

@ JukkaK.Korpela好点;我可以使用...链接添加到答案。 –

+0

答案是好的,但只是要注意,没有getComputedStyle()属性的borderWidth,但所有其他borderTopWidth,borderBottomWidth等...... – Hristo

相关问题