Here is my problem : the css style is not initialised when window.onload is triggered.
<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 a different file, if the style attribute is used (style="height=200px") it works.
Here is my problem : the css style is not initialised when window.onload is triggered.
<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 a different file, if the style attribute is used (style="height=200px") it works.
Share Improve this question asked Jan 23, 2013 at 20:05 IxDayIxDay 3,7072 gold badges24 silver badges27 bronze badges 04 Answers
Reset to default 6.style.height
does not show styles that e from CSS rules. It only returns styles that have been explicitly set on that object, either in the HTML or via javascript, not styles inherited from CSS rules.
Instead, you must use window.getComputedStyle()
. See the MDN doc for more details on how to use getComputedStyle()
properly. Here's one example:
window.getComputedStyle(document.getElementById('foo'),null).getPropertyValue("height");
Note: for older versions of IE, you have to either install a polyfill for getComputedStyle
or use el.currentStyle
.
Element.style will only be set for inline styles(<div id="foo" style="height: 200px"></div>
), to get the puted style use window.getComputedStyle
window.getComputedStyle(document.getElementById("foo"), null).getPropertyValue('height')
You can also consider working with jquery, a very popular javascript libraray with tons of very nice and powerfull features. And if you use the google cdn you don't need to worry about performance cause most browsers will already have the libray in cache.
To get the height of an element you would just use .height()
The full explanation is here http://api.jquery./height/
Your code would look something like this:
$(document).ready(function() {
console.log($('#foo).height());
});
It may look a bit confusing at first, but you will quickly get the hang of it, and you will be writing js a lot faster and more pact with jquery. I never go without it!
What you really want is either offsetHeight or clientHeight. Try this:
window.onload = function(){
console.log(document.getElementById('foo').offsetHeight);
};
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744506589a4577739.html
评论列表(0条)