仅在滚动时触发一次函数(scrollstop)

所以,我想在滚动时只触发一次函数(使用Scrollstop ,由stackoverflow答案给出)

问题是我不能只触发一次这个function。 我尝试了不同的解决方案(.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'); } 

(删除了计数器,因为它不起作用)

现场演示

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

如何使用变量来查看它是否先前被触发:

 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; } }); }; 

这是我在听滚动事件时触发一次函数的版本:

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

这个解决方案怎么样?

 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);