jQuery函数丢失被调用的元素,只保留最后一个调用者

时间:2013-10-10 16:00:21

标签: javascript jquery

我正在开发一个视差网站,我想在滚动停止时缓解这些元素。所以我开发了一个插件来检测滚动停止的时间,一旦它停止,然后平滑元素的移动(对象移动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

1 个答案:

答案 0 :(得分: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
    });
};

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