在JavaScript交互时,我们常常需要获取当前浏览器窗口的大小,从而进行定位元素等操作。不过获取各个版本浏览器窗口大小的方法都略有差异,当然我们可以使用jQuery等兼容多种浏览器的JavaScript框架来获取,但是有时我们又不希望引入第三方的JavaScript库,所以我们只能通过使用原生的JavaScript方法来获取。
以下代码定义了如何通过原生的JavaScript方法来获取浏览器窗口的大小:
// 定义获取窗口大小的方法
(function (window, undefined) {
// 定义获取窗口高度
if (typeof (window.getWindowHeight) != "function") {
window.getWindowHeight = function () {
var height = false;
if (window.innerHeight) {
height = window.innerHeight;
} else if (document.body && document.body.clientHeight) {
height = document.body.clientHeight;
}
if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
height = document.documentElement.clientHeight;
}
return height;
};
}
// 定义获取窗口宽度
if (typeof (window.getWindowWidth) != "function") {
window.getWindowWidth = function () {
var width = false;
if (window.innerWidth) {
width = window.innerWidth;
} else if (document.body && document.body.clientWidth) {
width = document.body.clientWidth;
}
if (document.documentElement && document.documentElement.clientHeight && document.documentElement.clientWidth) {
width = document.documentElement.clientWidth;
}
return width;
};
}
})(window);