0

我正在开发一个视差网站,我想在滚动停止时缓和元素。所以我开发了一个插件来检测滚动何时停止,一旦停止,然后平滑元素的移动(对象向用户滚动的方向移动 5 个像素)。它有效,但仅适用于插件应用到的最后一个元素。当我尝试调试时,我看到两个元素在内部仍然有效,$(window).scroll(function(event) {但是一旦我们到达$(window).scrollStopped(function(){,只有最后一个元素有效。有什么解决办法吗?

// Scroll Direction set
var lastScrollTop = 0, scrollDirection = "";
$(window).scroll(function(event){
   var st = $(this).scrollTop();
   if (st > lastScrollTop){
       scrollDirection = "down";
   } else {
      scrollDirection = "up";
   }
   lastScrollTop = st;
});

// Scroll Stopped detection
$.fn.scrollStopped = function(callback) {          
    $(this).scroll(function(){
        var self = this, $this = $(self);
        if ($this.data('scrollTimeout')) {
          clearTimeout($this.data('scrollTimeout'));
        }
        $this.data('scrollTimeout', setTimeout(callback,250,self));
    });
};

// Smooth ending
$.fn.smoothStop = function () {
        var $this = $(this);
        $(window).scroll(function(event) {

            $(window).scrollStopped(function(){
                var top = parseFloat($this.css("top"));

                if(scrollDirection == "down")
                {
                    console.log(top, $this);
                    var new_top = top + 5;
                     $this.animate({
                        top: new_top + 'px'},
                        1000);
                }
                else{
                    var new_top = top - 5;
                     $this.animate({
                        top: new_top + 'px'},
                        1000);
                }
            });
        });


    };

$(".g6").smoothStop(); $(".g2").smoothStop();

JSFIDDLE

4

1 回答 1

1
// Scroll Stopped detection
$.fn.scrollStopped = function(callback) {        
    $(this).scroll(function(){                      <-- this is the window
        var self = this, $this = $(self);
        if ($this.data('scrollTimeout')) {
          clearTimeout($this.data('scrollTimeout'));    <----timeout is removed from window
        }
        $this.data('scrollTimeout', setTimeout(callback,250,self)); <----timeout is set to window
    });
};

基本上,您正在尝试运行多个事件,但最终将这些多个事件存储在同一内存位置。因此,当您添加一个新条目时,它会取消之前的条目。

于 2013-10-10T16:22:42.123 回答