js判断滚动条是否到底部
作者:佳明妈 来源:web前端开发 2016-10-21 人气:5750使用js判断滚动条是否到底部,我们要用到scrollTop、clientHeight、scrollHeight这三个dom属性值,分别通过原生js实现判断滚动条是否到底部和jquery的方式实现判断滚动条到底部。以对象的方式
使用js判断滚动条是否到底部,我们要用到scrollTop、clientHeight、scrollHeight这三个dom属性值
判断滚动条的三个dom属性
scrollTop为滚动条在Y轴上的滚动距离。
clientHeight为内容可视区域的高度。
scrollHeight为内容可视区域的高度加上溢出(滚动)的距离。
由这些dom属性可知:滚动条到底部的公式为:scrollTop + clientHeight == scrollHeight
原生js语法判断滚动条是否到底部
//web前端开发http://www.51xuediannao.com/
var scrollToBottom = {
getScrollTop:function(){
var scrollTop = 0, bodyScrollTop = 0, documentScrollTop = 0;
if(document.body){
bodyScrollTop = document.body.scrollTop;
}
if(document.documentElement){
documentScrollTop = document.documentElement.scrollTop;
}
scrollTop = (bodyScrollTop - documentScrollTop > 0) ? bodyScrollTop : documentScrollTop;
return scrollTop;
},
getScrollHeight:function(){
var scrollHeight = 0, bodyScrollHeight = 0, documentScrollHeight = 0;
if(document.body){
bodyScrollHeight = document.body.scrollHeight;
}
if(document.documentElement){
documentScrollHeight = document.documentElement.scrollHeight;
}
scrollHeight = (bodyScrollHeight - documentScrollHeight > 0) ? bodyScrollHeight : documentScrollHeight;
return scrollHeight;
},
getClientHeight:function(){
var windowHeight = 0;
if(document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
}else{
windowHeight = document.body.clientHeight;
}
return windowHeight;
},
onScrollEvent:function(callback){
var This = this;
window.onscroll = function(){
if(This.getScrollTop() + This.getClientHeight() >= This.getScrollHeight()){
typeof callback == "function" && callback.call(this);
}
}
}
};
//我们来在 window 上注册onscroll事件来测试一下
scrollToBottom.onScrollEvent(function(){
alert("滚动条到底部了");
});
jquery实现判断滚动条是否到底部
当然必须先确认正确引入了jquery.js,实现代码如下:
//懒人建站整理编写
var $document = $(document);//缓存一下$(document)
$(window).scroll(function(){
var $this = $(this),
scrollTop = $this.scrollTop(),
scrollHeight = $document.height(),
windowHeight = $this.height();
if(scrollTop + windowHeight >= scrollHeight){
alert("jquery实现滚动条到底部判断了");
}
});
获取任意容器滚动条是否到底部
将document.body换成特定的容器,获取scrollTop和scrollHeight的方式不变,获取元素可见高度要使用offsetHeight属性,其他计算方法相同
↓ 查看全文
js判断滚动条是否到底部由懒人建站收集整理,您可以自由传播,请主动带上本文链接
懒人建站就是免费分享,觉得有用就多来支持一下,没有能帮到您,懒人也只能表示遗憾,希望有一天能帮到您。
js判断滚动条是否到底部-最新评论