如何在Internet explorer 8中获取innerWidth

How Do I Get innerWidth in Internet explorer 8

本文关键字:获取 innerWidth explorer Internet      更新时间:2023-09-26

在所有最近的浏览器中:

 window.innerWidth // 1920

在Internet explorer 8 中

 window.innerWidth // undefined

在IE8中获得此值的最佳方式是什么?

innerWidth由IE9而非IE8支持,您可以在以下位置执行此操作:

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;

上面的行将从IE以及其他符合标准的浏览器中获得宽度。


如果您使用jQuery,$(window).innerWidth()也会在所有浏览器中为您提供所需的结果。

为了得到这个,我仍然使用:

window.innerWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
window.innerHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

但要模仿真正的dom getter,请看以下内容:https://stackoverflow.com/a/18136089/1250044

对于ie8使用

document.documentElement.clientWidth

我知道innerWidth可能不太一样,但getBoundingClientRect也可以用于类似的容量:

elem = document.documentElement.getBoundingClientRect();
width = elem.getBoundingClientRect().right - elem.getBoundingClientRect().left;

您可以使用从IE 8获取此信息

document.documentElement.clientWidth

请注意,此值与IE 9为window.innerWidth返回的值不完全相同。

如果没有jQuery,您可以尝试此操作来获得heightwidth

var myWidth = 0, myHeight = 0;
if (typeof (window.innerWidth) == 'number') { //Chrome
     myWidth = window.innerWidth; 
     myHeight = window.innerHeight;
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
     myWidth = document.documentElement.clientWidth; 
     myHeight = document.documentElement.clientHeight;
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) { //IE9
     myWidth = document.body.clientWidth; 
     myHeight = document.body.clientHeight;
}
document.documentElement.clientWidth;

这用于ie8以获得客户端宽度

请注意:.innerWidth方法不适用于窗口和文档对象;对于这些,请改用.width()。

innerwidth()的jquery api文档