javascript:检测滚动结束

我有一个overflow设置为scrolldiv层。

当滚动到底部的div ,我想运行一个函数。

被接受的答案基本上是有缺陷的,现在已经被删除了。 正确的答案是:

 function scrolled(e) { if (myDiv.offsetHeight + myDiv.scrollTop >= myDiv.scrollHeight) { scrolledToBottom(e); } } 

在Firefox,Chrome和Opera上testing过。 有用。

我无法得到任何上述的答案,所以这里是第三个选项,适合我! (这与jQuery一起使用)

 if (($(window).innerHeight() + $(window).scrollTop()) >= $("body").height()) { //do stuff } 

希望这有助于任何人!

好的,这是一个好的和适当的解决scheme

你有一个id="myDiv"调用与id="myDiv"

所以function去。

 function GetScrollerEndPoint() { var scrollHeight = $("#myDiv").prop('scrollHeight'); var divHeight = $("#myDiv").height(); var scrollerEndPoint = scrollHeight - divHeight; var divScrollerTop = $("#myDiv").scrollTop(); if(divScrollerTop === scrollerEndPoint) { //Your Code //The Div scroller has reached the bottom } } 

这对我工作:

 $(window).scroll(function() { buffer = 40 // # of pixels from bottom of scroll to fire your function. Can be 0 if ($(".myDiv").prop('scrollHeight') - $(".myDiv").scrollTop() <= $(".myDiv").height() + buffer ) { doThing(); } }); 

必须使用jQuery 1.6或更高版本

我发现了一个可行的scheme。

这些答案都没有为我工作(目前在火狐22.0testing),经过大量的研究,我发现,似乎是一个更清洁和直接的解决scheme。

实施的解决scheme:

 function IsScrollbarAtBottom() { var documentHeight = $(document).height(); var scrollDifference = $(window).height() + $(window).scrollTop(); return (documentHeight == scrollDifference); } 

资源: http : //jquery.10927.n7.nabble.com/How-can-we-find-out-scrollbar-position-has-reached-at-the-bottom-in-js-td145336.html

问候

我基于Bjorn Tipling的回答创build了一个基于事件的解决scheme:

 (function(doc){ 'use strict'; window.onscroll = function (event) { if (isEndOfElement(doc.body)){ sendNewEvent('end-of-page-reached'); } }; function isEndOfElement(element){ //visible height + pixel scrolled = total height return element.offsetHeight + element.scrollTop >= element.scrollHeight; } function sendNewEvent(eventName){ var event = doc.createEvent('Event'); event.initEvent(eventName, true, true); doc.dispatchEvent(event); } }(document)); 

而你使用这样的事件:

 document.addEventListener('end-of-page-reached', function(){ console.log('you reached the end of the page'); }); 

顺便说一句:你需要添加这个JavaScript的JavaScript知道多久的网页

 html, body { height: 100%; } 

演示: http : //plnkr.co/edit/CCokKfB16iWIMddtWjPC?p=preview

看看这个例子: MDN Element.scrollHeight

我build议检查这个例子: stackoverflow.com/a/24815216 …实现了滚动操作的跨浏览器处理。

你可以使用下面的代码片段:

 //attaches the "scroll" event $(window).scroll(function (e) { var target = e.currentTarget, scrollTop = target.scrollTop || window.pageYOffset, scrollHeight = target.scrollHeight || document.body.scrollHeight; if (scrollHeight - scrollTop === $(target).innerHeight()) { console.log("► End of scroll"); } }); 

由于innerHeight在某些旧的IE版本中不起作用,可以使用clientHeight

 $(window).scroll(function (e){ var body = document.body; //alert (body.clientHeight); var scrollTop = this.pageYOffset || body.scrollTop; if (body.scrollHeight - scrollTop === parseFloat(body.clientHeight)) { loadMoreNews(); } });