什么是最可靠的方法来获得使用JavaScript的浏览器窗口的宽度/高度? [英] What is the most robust way to get the width/height of the browser window using JavaScript?

查看:132
本文介绍了什么是最可靠的方法来获得使用JavaScript的浏览器窗口的宽度/高度?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有curently使用follownig的条件,但他们没有跨浏览器的工作或根本:

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
}

我相信我缺少一个条件或两个 - 也许还有另一种常见的前pression我还没有考虑到

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?

推荐答案

您更好包裹整个逻辑成一个函数,所以你只要说 getWindowHeight()

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);
}

测试:IE5.5 +,FF 2+,铬,歌剧

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

但对于一个更可靠的方法,请访问相关comp.lang.javascript FAQ条目:结果
如何找到窗口的大小?

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?

这篇关于什么是最可靠的方法来获得使用JavaScript的浏览器窗口的宽度/高度?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆