您的位置:首页 > 编程语言 > PHP开发

GetPageSize和GetPageScroll:获取页面大小、窗口大小和滚动条位置

2013-06-09 14:41 567 查看
页面大小、窗口大小和滚动条位置这三个数值在不同的浏览器例如Firefox和IE中有着不同的实现。即使在同一种浏览器例如IE中,不同版本也有不同的实现。本文给出两个能兼容目前所有浏览器的Javascript函数,能够获得这三个数值。

GetPageSize能够获得页面大小和窗口大小。执行这个函数会得到一个包含页面宽度、页面高度、窗口宽度、窗口高度的对象。

//getPageSize()
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.body.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;
}

这个函数还是很容易读懂的。
第一部分是获得页面的实际大小,通过一个有3个分支的if...else语句实现。第1个分支针对Mozilla家族的浏览器例如Firefox;第2个分支针对普通IE浏览器;第3个分支针对IE Mac浏览器。
第二部分是获得窗口的实际大小,通过一个有3个分支的if...else语句实现。第1个分支针对Mozilla家族的浏览器例如Firefox;第2个分支针对Strict模式的IE 6.0 浏览器;第3个分支针对普通IE和其他浏览器。
第三个部分是在页面高度或者宽度少于窗口高度或者宽度的情况下,调整页面大小的数值。因为即使页面大小不足窗口大小,我们看到的仍然是窗口大小,所以调整后的数值更加符合实际需要。

GetPageScroll函数能够给出滚动条的位置。执行这个函数会得到一个包含滚动条水平位置和滚动条垂直位置的对象。

//getPageScroll()
function getPageScroll(){
var yScroll;
if (self.pageYOffset) {
yScroll = self.pageYOffset;
} else if (document.documentElement && document.documentElement.scrollTop){ // Explorer 6 Strict
yScroll = document.documentElement.scrollTop;
} else if (document.body) {// all other Explorers
yScroll = document.body.scrollTop;
}
arrayPageScroll = new Array('',yScroll)
return arrayPageScroll;
}

这个函数更为易读。它通过一个有3个分支的if...else语句实现。第1个分支针对Mozilla家族的浏览器例如Firefox;第2个分支针对Strict模式的IE 6.0 浏览器;第3个分支针对普通IE和其他浏览器。

可以通过下来完整的Html代码来测试一下这两个函数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: