javascript - css style not loaded when window.onload is triggered - Stack Overflow

Here is my problem : the css style is not initialised when window.onload is triggered.<div id="

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 0
Add a ment  | 

4 Answers 4

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条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信