仅在滚动时触发一次函数(scrollstop) [英] Only fire a function once on scroll (scrollstop)

查看:100
本文介绍了仅在滚动时触发一次函数(scrollstop)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

So, I'd like to fire a function only once on scroll (using Scrollstop, given by a stackoverflow answer)

问题在于我不会只触发一次这个功能。我尝试了不同的解决方案(.on(),设置一个计数器,在window.scrollstop函数外部/内部设置它)但没有任何效果。

The problem is that I don't get to fire the function only once. I've tried different solutions ( .on(), setting a counter, setting it outside/inside the window.scrollstop function) but nothing worked.

我不知道认为这很难,但是......到目前为止我没有让它成功。

I don't think it's difficult, but.. I didn't get to make it work so far.

这是我正在使用的插件

  $.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');
        }

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

(removed the counter since it didn't work)

这里的现场演示

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

PS: the function I'd like to make happen only once is the lazyPaint. It begins when we scroll to the element but it fires once again when it ends.

推荐答案

如何使用变量来查看是否它之前被解雇了:

how about using a variable to see whether it was previously fired:

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

这篇关于仅在滚动时触发一次函数(scrollstop)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆