用javascript在不同的浏览器中取窗口的可视高度和页面的内容高度是个烦心的事,所用的html标准不同、页面的内容高度是否超过窗口的可视高度都会对取值产生影响,所用到的取值方法也不同。
一、取窗口的可视高度(即浏览器的上面的工具栏到下面的状态栏之间的高度)
1、IE中的取法
document.getElementsByTagName("html")[0].offsetHeight;
2、Firefox、Chrome、Opera中取法
1 window.innerHeight;
二、取页面内容的高度(所有浏览器中的取法)
Math.max(document.getElementsByTagName("body")[0].scrollHeight, 窗口的可视高度)
三、完整的代码如下:
//窗口的可视高度
var windowHeight=document.all ? document.getElementsByTagName("html")[0].offsetHeight : window.innerHeight;
//页面的内容高度
var pageHeight=Math.max(windowHeight, document.getElementsByTagName("body")[0].scrollHeight);
可视宽度:
function getWidth(){
var xScroll
if (window.innerHeight && window.scrollMaxY)
{
xScroll = document.body.scrollWidth;
}
else if (document.body.scrollHeight > document.body.offsetHeight){
// all but Explorer Mac
xScroll = document.body.scrollWidth;
} else {
xScroll = document.body.offsetWidth;
}
var windowWidth
if (self.innerHeight) {
// all except Explorer
windowWidth = self.innerWidth;
} else if (document.documentElement && document.documentElement.clientHeight) {
// Explorer 6 Strict Mode
windowWidth = document.documentElement.clientWidth;
} else if (document.body) {
// other Explorers
windowWidth = document.body.clientWidth;
}
if(xScroll < windowWidth){
pageWidth = windowWidth;
} else {
pageWidth = xScroll;
}
return pageWidth;
}
Javascript得到当前页面可视高度和宽度
最新推荐文章于 2024-05-04 14:55:11 发布