判断滚动条到底部,需要用到DOM的三个属性值,即scrollTop、clientHeight、scrollHeight。
scrollTop为滚动条在Y轴上的滚动距离。
clientHeight为内容可视区域的高度。
scrollHeight为内容可视区域的高度加上溢出(滚动)的距离。
从这个三个属性的介绍就可以看出来,滚动条到底部的条件即为scrollTop + clientHeight == scrollHeight。
代码如下(兼容不同的浏览器)。
//滚动条在Y轴上的滚动距离
function getScrollTop(){
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;
}
//文档的总高度
function getScrollHeight(){
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;
}
//浏览器视口的高度
function getWindowHeight(){
var windowHeight = 0;
if(document.compatMode == "CSS1Compat"){
windowHeight = document.documentElement.clientHeight;
}else{
windowHeight = document.body.clientHeight;
}
return windowHeight;
}
window.onscroll = function(){
if(getScrollTop() + getWindowHeight() == getScrollHeight()){
alert("已经到最底部了!!");
// 这里可以调用接口请求数据了,滑动到底部自动加载数据
}
};
在日常开发中,监听窗口大小变化resize事件时,当一改变窗口大小会连续出发resize事件,事件处理函数简单的话还好,但是如果是复杂的dom操作,可能会导致整个UI卡顿设置浏览器奔溃,而我们往往的结果就是事件结束后处理函数执行一次就行了。于是我们可以通过函数的去抖/函数节流来处理。
函数调用n秒后才会执行,如果函数在n秒内被调用的话则函数不执行,重新计算执行时间。
/**函数的去抖动**/
function debounce(method,delay){
var timer=null;
return function(){
var context=this, args=arguments;
clearTimeout(timer);
timer=setTimeout(function(){
method.apply(context,args);
},delay);
}
}
function resizehandler(){
console.log(++n);
}
window.onresize=debounce(resizehandler,500);
函数的节流和函数的去抖都是通过减少实际逻辑处理过程的执行来提高事件处理函数运行性能的手段,并没有实质上减少事件的触发次数。
如果用jquery来实现的话就更简单了,如下所示:
$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if(scrollTop + windowHeight == scrollHeight){
alert("已经到最底部了!");
}
});