2013-06-01 70 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