2010-06-16 287 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。注意分号。