js window.scroll 怎么判断滚动到底部

JavaScript012

js window.scroll 怎么判断滚动到底部,第1张

若要想判断js window.scroll是否滚动到底部,需要用的三个属性值,它们分别是:

scrollTop、clientHeight和scrollHeight;

1、scrollTop为滚动条在Y轴上的滚动距离。

2、clientHeight为内容可视区域的高度。

3、scrollHeight为内容可视区域的高度加上溢出(滚动)的距离。

so,滚动条到底部的条件即为scrollTop + clientHeight == scrollHeight。

js判断window.scroll 判断滚动到底部的方法是设置一个变量,来检测鼠标位置。

具体的实现方法如下:

$(window).scroll(function() {

如果滚动的高度加上窗口的高度等于页面的高度就是到了底部

if($(window).scrollTop() + $(window).height() == $(document).height()) {

alert("bottom!")//已经滚动到底部

}

})

或者也可以写专用方法检测高度:

function getDocHeight() {

var D = document

return Math.max(

D.body.scrollHeight, D.documentElement.scrollHeight,

D.body.offsetHeight, D.documentElement.offsetHeight,

D.body.clientHeight, D.documentElement.clientHeight

)

}

然后再用以下方法检测:

$(window).scroll(function() {

if($(window).scrollTop() + $(window).height() == getDocHeight()) {

alert("bottom!")

}

})

在部分浏览器上,到底部时,触发不了

可以考虑:

1.用offsetHeight代替clientHeight ,多计算边框的距离

2.scrollTop的实时监听值可能是小数,采用Math.ceil(scrollTop),向上取整,避免少那个零点几的距离