原生JS与jQuery判断滚动条触底的方法

作者:竹影时间:2026-10-27 16:25:42浏览:217

本文介绍如何利用原生JavaScript和jQuery判断页面滚动条是否到达底部。核心原理涉及scrollTop、clientHeight与scrollHeight三个DOM属性的数值关系。文章提供了兼容不同浏览器的原生JS实现代码,以及更简洁的jQuery实现方式,并说明了如何判断特定元素内的滚动状态。

滚动条触底判断原理

要判断滚动条是否到达底部,主要依赖DOM中的三个关键属性:scrollTop、clientHeight和scrollHeight。

其中,scrollTop表示滚动条在垂直方向上滚动的距离。

clientHeight代表内容可视区域的高度,即浏览器窗口中可见部分的高度。

scrollHeight则是内容可视区域高度加上因溢出而产生的滚动距离,即内容的总高度。

基于上述定义,判断滚动条是否触底的逻辑条件为:scrollTop与clientHeight之和等于scrollHeight。

下面直接提供兼容不同浏览器的具体代码实现。


 

原生JavaScript实现方案

原生JavaScript实现代码如下:

//获取滚动条在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("you are in the bottom!");
 }
};

若使用jQuery库来实现,代码将更加简洁。


jQuery简化实现方案

jQuery实现代码如下:

$(window).scroll(function(){
var scrollTop = $(this).scrollTop();
var scrollHeight = $(document).height();
var windowHeight = $(this).height();
if(scrollTop + windowHeight == scrollHeight){
alert("you are in the bottom");
  }
});

特定元素滚动状态判断

若需判断特定元素内的滚动条是否触底,原理相同。只需将针对document.body的操作替换为特定元素,获取scrollTop和scrollHeight的方法不变,但获取可见高度时需使用offsetHeight属性,依此类推即可。

作者最新文章