2010-06-10 78 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