简体   繁体   中英

clientWidth and clientHeight always returns zero for ie7

I have no idea why, but clientWidth and clientHeight are always returning zero when I run this from IE in IE9 compat View, or IE7. It works for everything else. Very simple code snippet with problem (so that you can try it too): http://jsfiddle.net/nz2DA/

The code snippet found above is as follows... I have a page containing the following HTML snippet:

<div id='aaa'>aaaaaa</div>​

And my javascript to test the clientWidth and clientHeight functions are as follows:

var el = $('#aaa')[0];
alert('Client width and height: '+ el.clientWidth + ' X ' + el.clientHeight);​

This always pops up an alert with "0 X 0" when I run in IE7 or IE9 Compatibility mode.

Any help or explanation would really be appreciated. Thanks!

This is happening because of the "hasLayout" property in IE, and your div on its own does not "have layout". For more information, see http://www.satzansatz.de/cssd/onhavinglayout.html

Luckily you can trigger an element to have layout, which is why adding the "float:left" style works in the answer above. There are other triggers you can use too though that don't change the page. This one gives me proper values for clientWidth and clientHeight:

<div id="aaa" style="zoom: 1">aaaaaa</div>

The article says that setting "min-width: 0" should also work but it didn't for me. Setting "display: inline-block" worked OK but that might change your page. You can set these triggers in CSS so that the HTML doesn't need to change at all.

I tested your code and following are the observations.

in IE(sucks!), if you didn't apply any styles for the "aaa" element IE won't calculate any width and height. So JS simply give you 0. But if you look at the box model from the IE dev tool bar you will see some value. So if you use float:left to that element JS will return a value, which is correct and all browsers will give you the same output.

Since you are using jQuery why don't you use width() or outerWidth() or innerWidth() . These methods are generelaized for the every browsers. Simply if you use width() you will see a very large width since you didn't apply any styles. In IE if element doesn't have an float value it gets it's parent width.In your case it's window width.

So if I modify your code to get correct width and height would be:

HTML:

<div id="aaa" style="float:left;">aaaaaa</div>

JS:

var el = $('#aaa')[0];
alert('Client width and height: '+ el.clientWidth + ' X ' + el.clientHeight);

Please let me know if you need more clarifications... cheers!

尝试使用 Internet Explorer的offsetHeight属性。

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