Javascript clientWidth 和 clientHeight 返回 0
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11133069/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
clientWidth and clientHeight returns 0
提问by Sam
Why clientWidth/Height return 0 on IE, Chrome and Safari? but on Firefox and Opera works fine. I used this code:
为什么客户端宽度/高度在 IE、Chrome 和 Safari 上返回 0?但在 Firefox 和 Opera 上运行良好。我使用了这个代码:
$(document).ready(function () {
var imgs = document.getElementsByTagName('img');
var imgLength = imgs.length;
for (var i = 0; i <= imgLength - 1; i++) {
var imgWidth = imgs[i].clientWidth;
var imgHeight = imgs[i].clientHeight;
$('img').eq(i).attr({
width: imgWidth,
height: imgHeight
});
console.log(imgWidth);
}
console.log(imgLength);
});
any idea? Thanks.
任何的想法?谢谢。
I tried with window.load with clientwidth its works fine for Firefox, Chrome and Opera but he others not
我尝试使用带有 clientwidth 的 window.load 它对 Firefox、Chrome 和 Opera 工作正常,但其他人则不然
回答by Ramon Dekkers
Try change doctype.
http://forums.asp.net/post/1515655.aspx
I'm not sure, but I solved this problem so.
尝试更改文档类型。
http://forums.asp.net/post/1515655.aspx
我不确定,但我解决了这个问题。
回答by jazgot
If you want to get dimensions including margins and borders try using JQuery functions outerWidth
and outerHeight
. They should take care about crossbrowser differences. http://api.jquery.com/outerwidth/
如果您想获得包括边距和边框的尺寸,请尝试使用 JQuery 函数outerWidth
和outerHeight
. 他们应该注意跨浏览器的差异。http://api.jquery.com/outerwidth/
If you want to get only dimensions of an element contents (without margins, borders, paddings) use width
and height
. http://api.jquery.com/width/
如果您只想获取元素内容的尺寸(没有边距、边框、填充),请使用width
和height
。http://api.jquery.com/width/
回答by Subhajit
I think it would be better if you use JQuery to get the height and width, as it works fine in all browsers, so your code would be something like this :-
我认为如果您使用 JQuery 来获取高度和宽度会更好,因为它在所有浏览器中都可以正常工作,因此您的代码将是这样的:-
$(document).ready(function() {
var imgs = $('img');
var imgLength = imgs.length;
for(var i=0; i<= imgLength-1;i++){
var imgWidth = imgs[i].width();
var imgHeight = imgs[i].height();
$('img').eq(i).attr({width:imgWidth, height: imgHeight});
console.log(imgWidth);
}
console.log(imgLength);
});