Get the window height
This is frustrating me. It should be something really simple but I can't get it to work in IE. I want to get the height of the current window: Not the scroll height, not the document height, but the actual window height. I've tried window.innerHeight
which returns undefined
and document.documentElem开发者_如何学Goent.clientHeight
which gives the scroll height.
For current browsers
window.innerHeight
For IE 8 and lower, use
document.documentElement.offsetHeight;
If you need older browsers, use:
var height = "innerHeight" in window
? window.innerHeight
: document.documentElement.offsetHeight;
I'm using:
doc = document;
var theHeight = Math.max(
doc.body.scrollHeight, doc.documentElement.scrollHeight,
doc.body.offsetHeight, doc.documentElement.offsetHeight,
doc.body.clientHeight, doc.documentElement.clientHeight
);
Found it here: Get document height (cross-browser) - James Padolsey
And also found that jQuery is doing the same thing:
// 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 ]
);
http://www.javascripter.net/faq/browserw.htm
Note that the code that uses document.body.offsetWidth
and document.body.offsetHeight
must be executed after the browser has parsed the tag.
Update: Try this
<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>
Found here
精彩评论