在做网页的时候,有时候我们需要获取窗口可视范围的高度、文档内容实际高度、窗口滚动条滚动高度等,比如做返回顶部的按钮,就需要获取到当前窗口滚动条滚动高度。下面我们就来讲几个获取这些数据的方法。
JS:
/********************
* 取窗口滚动条滚动高度
******************/
function getScrollTop()
{
var scrollTop=0;
if(document.documentElement&&document.documentElement.scrollTop)
{
scrollTop=document.documentElement.scrollTop;
}
else if(document.body)
{
scrollTop=document.body.scrollTop;
}
alert(scrollTop);
}
/********************
* 取窗口可视范围的高度
*******************/
function getClientHeight()
{
var clientHeight=0;
if(document.body.clientHeight&&document.documentElement.clientHeight)
{
var clientHeight = (document.body.clientHeight
}
else
{
var clientHeight = (document.body.clientHeight>document.documentElement.clientHeight)?document.body.clientHeight:document.documentElement.clientHeight;
}
alert(clientHeight);
}
/********************
* 取文档内容实际高度
*******************/
function getScrollHeight()
{
ScrollHeight = Math.max(document.body.scrollHeight,document.documentElement.scrollHeight);
alert(ScrollHeight);
}
CSS:
#i1{
width: 100%;
height: 600px;
background: red;
}
#i2{
width: 100%;
height: 600px;
background: green;
}
#i3{
width: 100%;
height: 600px;
background: blue;
}
HTML:
getScrollTop
getClientHeight
getScrollHeight
下面是获取屏幕参数的几个方法:document.body.clientWidth ==> BODY对象宽度
document.body.clientHeight ==> BODY对象高度
document.documentElement.clientWidth ==> 可见区域宽度
document.documentElement.clientHeight ==> 可见区域高度