Css style not loading when window.onload is run
Here's my problem: css style is not initialized when window.onload is run.
<div id="foo"></div>
css file
#foo {
height: 200px
}
js file
window.onload = function(){
console.log(document.getElementById('foo').style.height);
};
the console displays: ""
the style must be in another file, if the style attribute is used (style = "height = 200px") it works.
.style.height
does not display styles that come from CSS rules. It only returns styles that have been explicitly set on that object, either in HTML or via javascript, and not in style inherited from CSS rules.
You should use instead window.getComputedStyle()
. For details on how to use it correctly getComputedStyle()
see MDN doc . Here's one example:
window.getComputedStyle(document.getElementById('foo'),null).getPropertyValue("height");
Note. For older versions of IE, you need to either install the polyfill for getComputedStyle
or use el.currentStyle
.
Element.style will only be set for inline styles ( <div id="foo" style="height: 200px"></div>
) to use computed style window.getComputedStyle
window.getComputedStyle(document.getElementById("foo"), null).getPropertyValue('height')
jquery - javascript . google cdn, , libray .
, .height()
http://api.jquery.com/height/
:
$(document).ready(function() {
console.log($('#foo).height());
});
, , js jquery. !
What you really want is either offsetHeight or clientHeight. Try the following:
window.onload = function(){
console.log(document.getElementById('foo').offsetHeight);
};