如何在Internet Explorer 8中获取innerWidth

60

在所有最新的浏览器中:

 window.innerWidth // 1920

在Internet Explorer 8中

 window.innerWidth // undefined

在IE8中获取这个值的最佳方法是什么?


1
你有没有尝试过 jQuery?使用它非常容易实现。 - Amar Palsapure
当然可以,$(window).innerWidth() 在 IE8 中也能正常工作,谢谢。 - antonjs
4
如果页面上有垂直滚动条,则 $(window).innerWidth() 返回的数字与 window.innerWidth 不同。 - Šime Vidas
8个回答

113

innerWidth在IE9中得到支持,但不支持IE8,您可以使用以下方法代替:

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

以上代码可在IE及其他标准兼容浏览器中获取宽度。


如果您使用jQuery,$(window).innerWidth()将在所有浏览器中给出所需的结果。


27
如果页面上显示垂直滚动条,$(window).innerWidth()返回的数字与window.innerWidth不同。 - Šime Vidas
6
根据jQuery文档所述,.innerWidth()方法不适用于窗口和文档对象。对于这些对象,请使用 .width() 方法。请参考 http://api.jquery.com/innerWidth/ 。 - Vignesh PT
1
即使在IE9(quirks)中,我仍需要使用document.body.clientWidth - jan

5
为了获得这个,我仍然使用以下方法:
window.innerWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
window.innerHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;

但是要模仿真实的DOM Getter,请看这个链接:https://dev59.com/aGkw5IYBdhLWcg3wDWPL#18136089

4

我知道innerWidth可能不是完全一样的,但是getBoundingClientRect也可以以类似的方式使用:

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

width = elem.getBoundingClientRect().right - elem.getBoundingClientRect().left;
  • 未捕获的类型错误:elem.getBoundingClientRect不是一个函数。 width = elem.right - elem.left;
  • 正确
- valeryan

4

适用于ie8

document.documentElement.clientWidth

2
你可以使用IE 8获取此信息。
document.documentElement.clientWidth

请注意,这个值不会和IE 9返回的window.innerWidth完全相同。


1

如果没有使用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;
}

1
“Chrome”这个注释是误导性的,因为所有现代浏览器都支持此属性:https://developer.mozilla.org/en-US/docs/Web/API/window.innerWidth?redirectlocale=en-US&redirectslug=DOM%2Fwindow.innerWidth#Browser_compatibility... 包括IE9,使“else if”过时。 - retrovertigo
1
你读了问题吗?OP要求提供适用于IE8的代码。 - Amar Palsapure
1
让我重新表述一下:“这使得第二个‘else if’变得过时了”。 - retrovertigo

0
document.documentElement.clientWidth;

这是用于IE8获取客户端宽度的


-1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接