2013-06-01 38 views
6

所以,我想上滚动火函数只有一次(使用Scrollstop,由计算器给出的答复)只有在滚动触发一个函数一次(scrollstop)

的问题是,我不明白只能触发一次该功能。我尝试了不同的解决方案(.on(),设置一个计数器,将它设置在window.scrollstop函数的外部/内部),但没有任何工作。

我不认为这很困难,但..我没有得到它到目前为止的工作。

下面是我使用

$.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,300,self)); 
      }); 
     }; 

和这里的插件是我的代码:

 $(window).scrollStopped(function(){ 
      if ($(".drawing1").withinViewport()) {  
       doNothing() 
       } 
      }) 


var doNothing = function() { 
      $('#drawing1').lazylinepainter('paint'); 
     } 

(除去柜台,因为它没有工作)

Live demo here

PS:我只想做一次的函数就是lazyPaint。它在我们滚动到元素时开始,但当它结束时再次触发。

+0

所以你的函数doNothing()实际上做了什么? –

+0

@roasted是的,愚蠢的函数名称,我知道:X – Naemy

回答

6

如何使用一个变量看它以前是否开除:

var fired = 0; 
$.fn.scrollStopped = function(callback) {   
      $(this).scroll(function(){ 
       if(fired == 0){ 
       var self = this, $this = $(self); 
       if ($this.data('scrollTimeout')) { 
        clearTimeout($this.data('scrollTimeout')); 
       } 
       $this.data('scrollTimeout', setTimeout(callback,300,self)); 
       fired = 1; 
       } 
      }); 
     }; 
+0

是的,我做到了,它确实有效。谢谢 ! – Naemy

+0

示例: https://jsfiddle.net/mnz02mnc/1/ – aWebDeveloper

6

这里是我有一次函数火的版本,同时听滚动事件:

var fired = false; 
window.addEventListener("scroll", function(){ 
    if (document.body.scrollTop >= 1000 && fired === false) { 
    alert('This will happen only once'); 
    fired = true; 
    } 
}, true) 
0

这个怎么样解?

function scrollEvent() { 
    var hT = $('#scroll-to').offset().top, 
    hH = $('#scroll-to').outerHeight(), 
    wH = $(window).height(), 
    wS = $(this).scrollTop(); 
    if (wS > (hT+hH-wH)){ 
    console.log('H1 on the view!'); 
    window.removeEventListener("scroll", scrollEvent); 
    } 
} 
window.addEventListener("scroll", scrollEvent); 
+1

尽管此代码片段可能是解决方案,[包括解释](// meta.stackexchange.com/questions/114762/explaining-entirely-基于代码的答案)确实有助于提高帖子的质量。请记住,您将来会为读者回答问题,而这些人可能不知道您的代码建议的原因。 – peacetype