使用 JavaScript 获取浏览器窗口宽度/高度的最可靠方法是什么?
我目前正在使用以下条件,但它们无法跨浏览器工作或根本无法工作:
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 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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
在您的页面中包含 jQuery 并使用
$(window).width()
和$(window).height()
。Include jQuery in your pages and use
$(window).width()
and$(window).height()
.您最好将整个逻辑包装到一个函数中,因此您只需说
getWindowHeight()
已测试:IE5.5+、FF 2+、Chrome、Opera
但要获得更强大的方法,请访问相关的 comp.lang.javascript 常见问题解答条目:
如何找到窗口的大小?
You better off wrapping the whole logic into a function, so you only have to say
getWindowHeight()
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?