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

zsbz8rwp  于 2023-01-30  发布在  jQuery
关注(0)|答案(5)|浏览(204)

因此,我希望在滚动时只触发一次函数(使用Scrollstop,由stackoverflow应答给出)
问题是我不能只触发一次函数,我尝试了不同的解决方案(. on(),设置一个计数器,将其设置在窗口外部/内部. 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
附言:我希望只发生一次的函数是lazyPaint。它在我们滚动到元素时开始,但在它结束时再次触发。

s4chpxco

s4chpxco1#

下面是我在监听scroll事件时触发一次函数的版本:

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

cig3rfwq2#

如何使用一个变量来查看它以前是否被激发过:

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

rbpvctlc3#

这些答案对我不起作用,所以这里是我的代码:

var fired = 0;
        jQuery(this).scroll(function(){
            if(fired == 0){
                alert("fired");
                fired = 1;
            }
        });
5ktev3wc

5ktev3wc4#

这个解决方案怎么样?

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

hmae6n7t5#

这个问题有点老了,但由于它是在我搜索“addeventlistener scroll once”时第一个弹出的,所以我将添加这个回复。现在有一个{ once: true }参数只触发一次事件。

window.addEventListener("scroll", () => {
/* your code here */
}, { once: true });

相关问题