2010-06-16 286 views
5

請提供洞察這個謎。使用document.getElementById()從css獲取值。style.height javascript

我試圖通過

var high = document.getElementById("hintdiv").style.height; 
alert(high); 

擺脫一個div框高度值,如果屬性包含div標籤裏我能得到這個值就好了,但它返回如果屬性爲空值在css部分中定義。

這很好,它顯示100px爲一個值。該值可以被訪問。

<div id="hintdiv" style="height:100px; display: none;"> 
. 
. 
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

這不好,它顯示一個空的警報屏幕。該值實際上是0。

#hintdiv 
{ 
height:100px 
display: none; 
} 

<div id="hintdiv"> 
. 
. 
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

但是我沒有問題訪問/改變「顯示:無」屬性是否是在該標籤或在CSS部分。 div框通過屬性定義方法(標籤內或CSS部分)正確顯示。

我也試圖通過其他的變化來訪問值,但沒有運氣

document.getElementById("hintdiv").style.height.value ----> undefined 
document.getElementById("hintdiv").height ---->undefined 
document.getElementById("hintdiv").height.value ----> error, no execution 

任何解決方案?

TIA。

+4

請參閱http://stackoverflow.com/questions/1098349/reading-non-inline-css-style-info-from-javascript和http://stackoverflow.com/questions/1048336/cant-access-css- selectors-properties-from-javascript – 2010-06-16 01:51:50

+0

另請參閱:http://gist.github.com/369133和http://stackoverflow.com/questions/2531737/javascript-incapable-of-getting-elements-max-height-via -element-style-maxheight/ – CMS 2010-06-16 02:14:42

+0

謝謝大家,這當然是意想不到的。我想我會爲這個1(或2個元素)做內聯樣式。 – Jamex 2010-06-16 02:26:27

回答

-1

你應該考慮使用jQuery來代替它......它將簡化爲$('#hintDiv')。height()並且它總是會返回div的實際寬度。

+3

width!==高度:) – epascarello 2010-06-16 02:12:59

+0

謝謝DevIT,我需要拿起一本jQuery書。 – Jamex 2010-06-16 02:24:31

+0

嗨epascarello!很高興我能幫上忙......但是對於jQuery來說,你絕對不需要一本書,只需在jQuery網站上試試教程:http://docs.jquery.com/Tutorials – 2010-06-17 18:34:24

5

這是因爲,當您使用document.getElementById("hintdiv").style.height;時,您正在訪問標記的style屬性。如果該屬性不存在,那麼您將得不到任何值。

相反,您應該在IE瀏覽器中使用currentStyle對象,並在其餘網頁瀏覽器中使用getComputedStyle()功能。

1

您的CSS語法錯誤,它應該是height:100px;而不是height:100px。注意分號。