1. 程式人生 > >jQuery scroll結束事件和resize結束事件

jQuery scroll結束事件和resize結束事件

通過設定timeout,判斷滾動事件和resize事件的結束

scroll end事件

$.fn.scrollEnd = function(callback, timeout) {          
  $(this).scroll(function(){
    var $this = $(this);
    if ($this.data('scrollTimeout')) {
      clearTimeout($this.data('scrollTimeout'));
    }
    $this.data('scrollTimeout', setTimeout(callback,timeout));
  });
};

//with a 1000ms timeout
$(window).scrollEnd(function(){
    alert('stopped scrolling');
}, 1000);

resize end事件
$.fn.resizeEnd = function (callback, timeout) {
    $(this).resize(function () {
        var $this = $(this);
        if ($this.data('resizeTimeout')) {
            clearTimeout($this.data('resizeTimeout'));
        }
        $this.data('resizeTimeout', setTimeout(callback, timeout));
    });
};

$(document).resizeEnd(function () {
    alert('stopped resizing');
}, 800);

https://stackoverflow.com/questions/3701311/event-when-user-stops-scrolling