jQuery Callback on end of page scroll

2019-05-06 17:11发布

i have a div tag which is set to overflow:scroll in css.
i have a callback which is supposed to be called on the end of scroll of the element which is found using this.

$('#details').scroll( function () {  
    if ($(this).height() == ($(this).get(0).scrollHeight - $(this).scrollTop())) {  
        getDetails($("span:last").attr("id"), 3);  
    }  
});  

where getDetails is the callback im using. it takes the last element of the span inside a div and sends it as a value. its all ajax calls. problem is getDetails gets called thrice everytime i hover to the end of the div. any suggestions on how i make it to be called once?

The repeated callback happens only when i use the scroll wheel or press the scroll bar button to go down. Everything works fine when scrollbar is dragged.

2条回答
混吃等死
2楼-- · 2019-05-06 17:44

You should defer handling of events that have constant feedback, such as scroll and resize events, by using setTimeout/clearTimeout. When the event you want to handle is raised, a call to your intended handler in a setTimeout with a reasonable duration, but keep a reference to the handle setTimeout returns. Now, modify that same code to check for the presence of this handle, and if it exists, clearTimeout and update the handle to a new setTimeout call.

Here is a working example: http://jsfiddle.net/SBgXA/

       var timeoutHandle;

       var handler =  function(e) {
              alert('raised'); // put your code here
              if ($(this).height() == ($(this).get(0).scrollHeight - $(this).scrollTop()) {  
                getDetails($("span:last").attr("id"), 3);  
              }
       }

       $('#details').scroll(function(e) {
           clearTimeout(timeoutHandle);

           timeoutHandle = setTimeout(function() {
             handler(e);
           }, 100);
       });
查看更多
We Are One
3楼-- · 2019-05-06 17:45

I didn't test this, but something along these lines might work. Its quite hacky though...

$('#details').data("didfire", false).scroll( function () {  
    if ($(this).height() == ($(this).get(0).scrollHeight - $(this).scrollTop())) {  
        if(!$(this).data("didfire")) {
            getDetails($("span:last").attr("id"), 3);  

            $(this).data("didfire", true)
            var ref = $(this);
            setTimeout(function(){
                ref.data("didfire", false);
            }, 500);
        }
    }  
}); 
查看更多
登录 后发表回答