其实很简单我们只要使用到clientheight、offsetheight、scrolltop这三个参数就可以判断我们当前位置了,具体来给大家介绍一个例子。
例子,判断到底部
代码如下
$(window).scroll(function () {
if ($(document).scrolltop() + $(window).height() >= $(document).height()) {
alert("哦哦,到底了.");
}
});
如果要实现拉到底部自动加载内容。只要注册个滚动条事件:
首先,我们拉动滚动条,从最上面拉到最下面,变化的是scrolltop的值,而这个值是有一个区间的。
这个区间是: [0, (offsetheight - clientheight)]
即,滚动条拉动的整个过程的变化在 0 到 (offsetheight – clientheight) 范围之内。
1、判断滚动条滚动到最底端: scrolltop == (offsetheight – clientheight)
2、在滚动条距离底端50px以内: (offsetheight – clientheight) – scrolltop <= 50
3、在滚动条距离底端5%以内: scrolltop / (offsetheight – clientheight) >= 0.95
代码如下
scrollbottomtest =function(){
$("#contain").scroll(function(){
var $this =$(this),
viewh =$(this).height(),//可见高度
contenth =$(this).get(0).scrollheight,//内容高度
scrolltop =$(this).scrolltop();//滚动高度
//if(contenth - viewh - scrolltop <= 100) { //到达底部100px时,加载新内容
if(scrolltop/(contenth -viewh)>=0.95){ //到达底部100px时,加载新内容
// 这里加载数据..
}
});
}
js的判断
判断垂直滚动条是否到达底部
廓清了以上的概念,编码其实就比较简单了, 以下是示例代码:
代码如下
<!doctype html public "-//w3c//dtd xhtml 1.0 transitional//en" "http://www.w3.org/tr/xhtml1/dtd/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="content-type" content="text/html;charset=utf-8">
<title>下拉滚动条滚到底部了吗?</title>
<script language="javascript" src="jquery-1.4.2.min.js"></script>
<script language="javascript">
$(document).ready(function (){
var nscrollhight = 0; //滚动距离总长(注意不是滚动条的长度)
var nscrolltop = 0; //滚动到的当前位置
var ndivhight = $("#div1").height();
$("#div1").scroll(function(){
nscrollhight = $(this)[0].scrollheight;
nscrolltop = $(this)[0].scrolltop;
if(nscrolltop + ndivhight >= nscrollhight)
alert("滚动条到底部了");
});
});
</script>
<body>
<div id="div1" style="overflow-y:auto; overflow-x:hidden; height:500px;">
<div style="background-color:#ccc; height:750px;">ie 和 ff 下测试通过</div>
</div>
</body>
</html>
代码解说:
内部div高度为750,外部div高度为500,所以垂直滚动条需要滚动750-500=250的距离,就会到达底部,参见语句nscrolltop + ndivhight >= nscrollhight。
程序中,在外部div的scroll(滚动)事件中侦测和执行if判断语句,是非常消耗cpu资源的。用鼠标拖拉滚动条,只要有一个像素的变动就会触发该事件。但点击滚动条两头的箭头,事件触发的频率会低得多。所以滚动条的scroll事件要谨慎使用。
本示例判断的是没有水平滚动条的情况,在有水平滚动条时,情况会有细小的变化,所以nscrolltop + ndivhight >= nscrollhight语句中,需要用“>=”比较运算符,而没有水平滚动条的时候,等号“=”就足够了。大家可以实际测试一下。还可以判断水平滚动条是否滚动到头了。
以上就是jquery判断滚动条滚到页面底部脚本的详细内容。