2010-06-10 79 views
29

这令我很沮丧。它应该是非常简单的东西,但我不能让它在IE中工作。我想获得当前窗口的高度:不是滚动高度,不是文档高度,而​​是实际的窗口高度。我试过window.innerHeight,它返回undefineddocument.documentElement.clientHeight,它给出了滚动高度。获取窗口高度

回答

68

对于IE 8和更低,使用

document.documentElement.offsetHeight; 

所以跨浏览器应该是:

var height = "innerHeight" in window 
       ? window.innerHeight 
       : document.documentElement.offsetHeight; 
+1

安迪,Flippen唉男人,它的工作原理,谢谢 – 2010-06-10 08:35:48

+0

我添加'window.innerHeight'是为IE9 + – vsync 2014-08-13 10:12:40

+0

我成功地使用这种技术在基于页面的页面在IE 8/9/10和Firefox下也是如此。 Thankyou – 2014-08-26 07:21:08

1

http://www.javascripter.net/faq/browserw.htm

注意,在浏览器解析标签后,使用 document.body.offsetWidthdocument.body.offsetHeight代码必须执行。

更新: 试试这个

<script type="text/javascript"> 
<!-- 

var viewportwidth; 
var viewportheight; 

// the more standards compliant browsers (mozilla/netscape/opera/IE7) use window.innerWidth and window.innerHeight 

if (typeof window.innerWidth != 'undefined') 
{ 
     viewportwidth = window.innerWidth, 
     viewportheight = window.innerHeight 
} 

// IE6 in standards compliant mode (i.e. with a valid doctype as the first line in the document) 

else if (typeof document.documentElement != 'undefined' 
    && typeof document.documentElement.clientWidth != 
    'undefined' && document.documentElement.clientWidth != 0) 
{ 
     viewportwidth = document.documentElement.clientWidth, 
     viewportheight = document.documentElement.clientHeight 
} 

// older versions of IE 

else 
{ 
     viewportwidth = document.getElementsByTagName('body')[0].clientWidth, 
     viewportheight = document.getElementsByTagName('body')[0].clientHeight 
} 
document.write('<p>Your viewport width is '+viewportwidth+'x'+viewportheight+'</p>'); 
//--> 
</script> 

找到here

+0

不,不工作,给人的滚动高度 – 2010-06-10 08:16:52

+0

@YO Momma:你可以使用下面的代码:myWidth = screen.availWidth; myHeight = screen.availHeight;'这适用于所有浏览器。一件事是那个window.innerheight不支持在IE – Raje 2011-08-25 09:05:20

5

我使用:

doc = document; 
var theHeight = Math.max(
    doc.body.scrollHeight, doc.documentElement.scrollHeight, 
    doc.body.offsetHeight, doc.documentElement.offsetHeight, 
    doc.body.clientHeight, doc.documentElement.clientHeight 
); 

在这里找到它: Get document height (cross-browser) - James Padolsey

而且还发现jQuery正在做同样的事情:

// Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest 
// unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. 
return Math.max(
    elem.body[ "scroll" + name ], doc[ "scroll" + name ], 
    elem.body[ "offset" + name ], doc[ "offset" + name ], 
    doc[ "client" + name ] 
); 
+0

误导。由于'scrollHeight'给出[元素内容的高度,包括屏幕上不可见的内容](https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollHeight),代码给出* *文件高度**。但问题是获得**窗口高度**。 – Lightman 2016-07-23 07:48:32