准确获取页面与窗口尺寸的JavaScript实现

作者:半夏

时间:2026-10-28

浏览:533

本文介绍如何使用JavaScript准确获取网页文档的滚动高度与宽度,以及浏览器可视窗口的高度与宽度。代码通过判断不同浏览器内核(如IE、Firefox、Safari)的属性支持情况,处理滚动条及视口差异,最终返回包含页面宽高和窗口宽高的数组,适用于需要动态布局或响应式设计的场景。

文章目录

JavaScript获取页面与窗口尺寸代码实现

function getPageSize(){



var xScroll, yScroll;



if (window.innerHeight && window.scrollMaxY) {


xScroll = document.body.scrollWidth;


yScroll = window.innerHeight + window.scrollMaxY;


} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac


xScroll = document.body.scrollWidth;


yScroll = document.body.scrollHeight;


} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari


xScroll = document.body.offsetWidth;


yScroll = document.offsetHeight;


}

var windowWidth, windowHeight;


if (self.innerHeight) { // all except Explorer


windowWidth = self.innerWidth;


windowHeight = self.innerHeight;


} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode


windowWidth = document.documentElement.clientWidth;


windowHeight = document.documentElement.clientHeight;


} else if (document.body) { // other Explorers


windowWidth = document.body.clientWidth;


windowHeight = document.body.clientHeight;


}

// for small pages with total height less then height of the viewport


if(yScroll < windowHeight){


pageHeight = windowHeight;


} else {


pageHeight = yScroll;


}

// for small pages with total width less then width of the viewport


if(xScroll < windowWidth){


pageWidth = windowWidth;


} else {


pageWidth = xScroll;


}


arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight)


return arrayPageSize;


}

有幸找到了你的这个东东,帮我解决了问题,不过仔细看了下,好象大大的有点问题,参数值和名称上看好象有点对不上号哦.


// for small pages with total height less then height of the viewport


if(yScroll < windowHeight){


pageHeight = yScroll;


} else {


pageHeight = windowHeight;


} 

// for small pages with total width less then width of the viewport


if(xScroll < windowWidth){


pageWidth = xScroll;


} else {


pageWidth = windowWidth;


}

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章