2014-01-23 37 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

相關問題