如何在Internet Explorer 8中获取innerWidth

ant*_*njs 59 javascript

在最近的浏览器中:

 window.innerWidth // 1920
Run Code Online (Sandbox Code Playgroud)

在Internet Explorer 8中

 window.innerWidth // undefined
Run Code Online (Sandbox Code Playgroud)

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

Sar*_*raz 113

innerWidth由IE9不支持IE8,你可以这样做insteaad:

var width = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
Run Code Online (Sandbox Code Playgroud)

以上行将为您提供IE以及其他符合标准的浏览器的宽度.


如果你使用jQuery,$(window).innerWidth()也会在所有浏览器中给你想要的结果.

  • `$(window).innerWidth()`如果页面上显示垂直滚动条,则不会返回与`window.innerWidth`相同的数字. (27认同)
  • .innerWidth()不适用于窗口和文档对象,如jquery文档中所述.http://api.jquery.com/innerWidth/"此方法不适用于窗口和文档对象;对于这些,请改用.width()." (6认同)

yck*_*art 5

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

window.innerWidth = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
window.innerHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
Run Code Online (Sandbox Code Playgroud)

但要模仿真正的dom-getter看看这个:https://stackoverflow.com/a/18136089/1250044