使用$(window).width(),window.outerWidth,window.innerWidth,docu

时间:2022-02-24 07:18:02

下面先以谷歌为例做数据分析,兼容性问题后面再说。

先上一张图(图最好理解):

firebug打印结果:

使用$(window).width()与$(window).height():1349 392 使用window.outerWidth与window.outerHeight:1366 728 使用window.innerWidth与window.innerHeight:1366 392 使用document.documentElement.clientWidth与document.documentElement.clientHeight:1349 392 使用document.body.clientWidth与document.body.clientHeight:1349 2970

可以得出如下结论:

$(window).width()与$(window).height():获得的是屏幕可视区域的宽高,不包括滚动条与工具条。

window.outerWidth与window.outerHeight:获得的是加上工具条与滚动条窗口的宽度与高度。

window.innerWidth与window.innerHeight:获得的是可视区域的宽高,但是宽度包含了纵向滚动条的宽度。

document.documentElement.clientWidth与document.documentElement.clientHeight:获得的是屏幕可视区域的宽高,不包括滚动条与工具条,跟jquery的$(window).width()与$(window).height()获得的结果是一样的。

document.body.clientWidth与document.body.clientHeight:document.body.clientWidth获得的也是可视区域的宽度,但是document.body.clientHeight获得的是body内容的高度,如果内容只有200px,那么这个高度也是200px,如果想通过它得到屏幕可视区域的宽高,,需要样式设置,如下:

body { height: 100%; overflow: hidden; } body, div, p, ul { margin: 0; padding: 0; }

最关键的是:body的height:100%影响document.body.clientHeight的值。

body的margin:0,padding:0影响document.body.clientWidth的值。

火狐浏览器数据分析:

使用$(window).width()与$(window).height():1349 358 使用window.outerWidth与window.outerHeight:1382 744 使用window.innerWidth与window.innerHeight:1366 358 使用document.documentElement.clientWidth与document.documentElement.clientHeight:1349 358 使用document.body.clientWidth与document.body.clientHeight:1349 3630

得到的结果跟上面差不多,但是有区别的是window.outerWidth得到的值是1382,与window.innerWidth宽度不一样。(没弄清楚多余的16px是哪儿来的)。

IE9以及以上的版本浏览器得到的结果跟火狐的一样,这儿不贴数据了。

IE8以及更低的版本不识别window.outerWidth与window.innerWidth方法,得到的值为undefined。

兼容性:

1.window innerWidth 和 innerHeight 属性与outerWidth和outerHeight属性IE8以及以下不支持。

2.测试浏览器IE,火狐,谷歌,360浏览器,Safari都支持document.documentElement.clientWidth与document.documentElement.clientHeight。

结论:

获取屏幕的可视区域的宽高可使用jquery的方式获得,也可以使用原生js获得,即:

document.documentElement.clientWidth与document.documentElement.clientHeight

使用$(window).width(),window.outerWidth,window.innerWidth,document.documentElement.clientWidth,document.body.clientWidth的区别与兼容分析