What is the most robust way to get the width/height of the browser window using JavaScript?

陌路散爱 提交于 2019-12-11 13:38:17

问题


I am curently using the follownig conditions, but they aren't working across browsers or at all:

if (typeof (window.innerHeight) == 'number') {
    //Non-IE:
    //Perform operation using window.innerWidth/Height
} else if (document.documentElement && (document.documentElement.clientWidth || document.documentElement.clientHeight)) {
    //IE 6+ in 'standards compliant mode'
    //Perform operation using document.documentElement.clientWidth/Height
} else if (document.body && (document.body.clientWidth || document.body.clientHeight)) {
    //IE 4 compatible
    //Perform operation using document.body.clientWidth/Height
}

I believe I am missing a condition or two - perhaps there is another common expression I haven't taken into account.

What do I need to add to make this complete?


回答1:


You better off wrapping the whole logic into a function, so you only have to say getWindowHeight()

// cross browser window height
function getWindowHeight() {
  return window.innerHeight || 
         (document.documentElement && document.documentElement.clientHeight) || 
         (document.body && document.body.clientHeight);
}

Tested: IE5.5+, FF 2+, Chrome, Opera

But for an even more robust approach please visit the related comp.lang.javascript FAQ entry:
How do I find the size of the window?




回答2:


Include jQuery in your pages and use $(window).width() and $(window).height().



来源:https://stackoverflow.com/questions/4126790/what-is-the-most-robust-way-to-get-the-width-height-of-the-browser-window-using

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!