10

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

问题是我不能只触发一次该功能。我尝试了不同的解决方案(.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:我只想实现一次的功能是lazyPaint。它在我们滚动到元素时开始,但在结束时再次触发。

4

4 回答 4

7

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

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;
              }
          });
      };
于 2013-06-02T13:41:51.497 回答
7

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

var fired = false;
window.addEventListener("scroll", function(){
  if (document.body.scrollTop >= 1000 && fired === false) {
    alert('This will happen only once');
    fired = true;
  }
}, true)
于 2013-07-03T21:36:07.330 回答
4

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

        var fired = 0;
        jQuery(this).scroll(function(){
            if(fired == 0){
                alert("fired");
                fired = 1;
            }
        });
于 2020-09-02T09:35:02.370 回答
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);
于 2018-02-04T16:03:52.623 回答