2012-06-13 39 views
2

我的HTML:<div id="bar" ></div>的getComputedStyle或currentStyle的左邊框寬度

我的CSS:

#bar 
{ 
    border-left-width:150px; 
} 

我的JS:

function getStyle(el,styleProp) 
{ 
    if(el.currentStyle)var y=el.currentStyle[styleProp]; 
    else if(window.getComputedStyle)var y=document.defaultView.getComputedStyle(el,null).getPropertyValue(styleProp); 
    return y; 
} 

alert(getStyle(document.getElementById("bar"),"border-left-width"));//Outputs 0px 

小提琴:http://jsfiddle.net/4ABhZ/1

哪有我收到border-left-width屬性? (我爲例它不工作(在Firefox))

+0

http://jsfiddle.net/L2ZwD/ .................... – user1365010

+0

你的jsfiddle說「0px」 –

+0

是的,這是正確的。給div一些尺寸和顏色,你會看到爲什麼:http://jsfiddle.net/mattball/Xkxgk/ –

回答

2

檢查border-left-style財產。它設置爲none(默認值)。將其設置爲solid之類的內容,然後您就可以繼續使用:http://jsfiddle.net/Paulpro/4ABhZ/4/

+1

在這裏說「未定義」 - 歌劇所以不crossbrowser更好,你使用jquery(crossbrowser) –

1

要支持較舊的瀏覽器,您需要將連字符-css更改爲camelCase。

您也可以在其他瀏覽器中使用camelCase,並且 直接讀取getComputedStyle對象的屬性。

function getStyle(el, css){ 
    if(window.getComputedStyle) return getComputedStyle(el, '')[css]; 
    if(el.currentStyle) return el.currentStyle[css];  
} 

警報(對getStyle(的document.getElementById( '巴'), 'borderTopWidth'));

注意 - 在CSS定義需要風格以及爲邊框的寬度有一個計算寬度(並且不能設置爲顯示:沒有,當你計算出它的尺寸......)