[removed] do an action after user is done scrolling

后端 未结 5 1913
被撕碎了的回忆
被撕碎了的回忆 2020-12-01 06:55

I\'m trying to figure out a way to do this. I have a list of boxes, each about 150px high. I am using javascript (and jquery) and want that, after a user scroll

相关标签:
5条回答
  • 2020-12-01 07:16

    This would be a scenario, where vanilla JavaScript would be useful.

    var yourFunction = function(){
      // do something computationally expensive
    }
    
    $(window).scroll(function(){
      yfTime=setTimeout("yourFunction()",250);
    });
    
    0 讨论(0)
  • 2020-12-01 07:17

    As you are already using jQuery, have a look at Ben Alman's doTimeout plugin which already handles the debouncing of methods (which is what you are after).

    Example shamelessly stolen from his website:

    $(window).scroll(function(){
       $.doTimeout( 'scroll', 250, function(){
          // do something computationally expensive
       });
    });
    
    0 讨论(0)
  • 2020-12-01 07:25

    This is basically the same as Šime Vidas' answer, but less complex:

    var scrollTimeout = null;
    $(window).scroll(function(){
        if (scrollTimeout) clearTimeout(scrollTimeout);
        scrollTimeout = setTimeout(function(){yourFunctionGoesHere()},500);
    });
    

    500 is the delay. Should be ok for mouse scroll.

    0 讨论(0)
  • 2020-12-01 07:25

    Sure, in the event handler for the scroll event, fire off a setTimeout for 100 or 200 milliseconds later. Have that setTimeout function you set inside of the scroll event handler do the positioning logic you mention above. Also have the scroll event handler clear any timeouts set by itself. This way, the last time the scroll event fires, the setTimeout function will get to complete as the scroll event has not cleared it.

    0 讨论(0)
  • 2020-12-01 07:33

    The code:

    var scrollTimeout = null;
    var scrollendDelay = 500; // ms
    
    $(window).scroll(function() {
        if ( scrollTimeout === null ) {
            scrollbeginHandler();
        } else {
            clearTimeout( scrollTimeout );
        }
        scrollTimeout = setTimeout( scrollendHandler, scrollendDelay );
    });
    
    function scrollbeginHandler() {
        // this code executes on "scrollbegin"
        document.body.style.backgroundColor = "yellow";
    }
    
    function scrollendHandler() {
        // this code executes on "scrollend"
        document.body.style.backgroundColor = "gray";
        scrollTimeout = null;
    }
    
    0 讨论(0)
提交回复
热议问题