I would like a method of getting the available window size across multiple browsers without using jQuery/Mootools/any third-party library dependencies. I've done a little research on this but开发者_开发技巧 half the things I've come across talk about Netscape Navigator...
Just wondering if someone out there has more recent advice.
For modern browsers:
document.documentElement.clientHeight
is all you need.
usage
var width = getWindowSize().width;
code
var getWindowSize = (function() {
var docEl = document.documentElement,
IS_BODY_ACTING_ROOT = docEl && docEl.clientHeight === 0;
// Used to feature test Opera returning wrong values
// for documentElement.clientHeight.
function isDocumentElementHeightOff () {
var d = document,
div = d.createElement('div');
div.style.height = "2500px";
d.body.insertBefore(div, d.body.firstChild);
var r = d.documentElement.clientHeight > 2400;
d.body.removeChild(div);
return r;
}
if (typeof document.clientWidth == "number") {
return function () {
return { width: document.clientWidth, height: document.clientHeight };
};
} else if (IS_BODY_ACTING_ROOT || isDocumentElementHeightOff()) {
var b = document.body;
return function () {
return { width: b.clientWidth, height: b.clientHeight };
};
} else {
return function () {
return { width: docEl.clientWidth, height: docEl.clientHeight };
};
}
})();
Note: The dimensions cannot be determined accurately until after the document has finished loading.
from comp.lang.javascript FAQ
This is not a perfect solution, but it is lightweight & suitable for most purposes:
var WX,WY;
if( window.innerWidth )
{
WX = window.innerWidth;
WY = window.innerHeight;
} else {
WX = document.body.clientWidth;
WY = document.body.clientHeight;
}
精彩评论