简体   繁体   中英

get value from css using document.getElementById().style.height javascript

Please offer insight into this mystery.

I am trying to get the height value from a div box by

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

I can get this value just fine if the attribute is contained within the div tag, but it returns a blank value if the attribute is defined in the css section.

This is fine, it shows 100px as a value. The value can be accessed.

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

This is not fine, it shows an empty alert screen. The value is practically 0.

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

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

But I have no problem accessing/changing the "display:none" attribute whether it is in the tag or in the css section. The div box displays correctly by both attribute definition methods (inside the tag or in the css section).

I also tried to access the value by other variations, but no luck

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

Any solution?

TIA.

This is because, when you use document.getElementById("hintdiv").style.height; you are accessing the style attribute of the tag. If the attribute is not there , then you get no values.

Instead you should use currentStyle object in IE and getComputedStyle() function in the rest of web browsers.

You CSS syntax is wrong, it sould be height:100px; rather than height:100px . Note the semicolon.

您应该考虑使用usign jQuery ...它将简化为$('#hintDiv')。height(),并将始终返回div的实际宽度。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM