将jQuery(.off)隔离到滚动上的一个特定元素

问题描述 投票:0回答:2

我一直在使用这个滚动计数脚本,当您向下滚动到页面上的特定位置时,它会激活一些数字。到目前为止,一切都按预期工作,但我注意到在脚本中杀死了页面上其他所有其他jQuery滚动事件。这就是我所拥有的:

//count up script
  $(function () {
    var fx = function fx() {
      $(".stat-number").each(function (i, el) {
        var data = parseInt(this.dataset.n, 10);
        var props = {
          "from": {
            "count": 0
          },
          "to": {
            "count": data
          }
        };
        $(props.from).animate(props.to, {
          duration: 500 * 1,
          step: function (now, fx) {
            $(el).text(Math.ceil(now));
          },
          complete:function() {
            if (el.dataset.sym !== undefined) {
              el.textContent = el.textContent.concat(el.dataset.sym)
            }
          }
        });
      });
    };

    var reset = function reset() {
      console.log($(this).scrollTop())
      if ($(this).scrollTop() > 1300) {
        fx()
        $(this).off("scroll");
      }
    };

    $(window).on("scroll", reset);
  });

//Other scroll script
  $(window).scroll(function() {
    var sT = $(this).scrollTop();
    if (sT > 40) {
      $('.header').addClass('nav-bg');
    } else {
      $('.header').removeClass('nav-bg');
    }
  });

所以我不确定的棘手部分是如何使两个脚本彼此分开操作。如果我在count up脚本中修改$(this).off("scroll");,那么每次滚动时动画都会一直触发。如果我离开$(this).off("scroll");,它会破坏页面上的所有滚动事件。总的来说,我知道为什么它正在做它正在做的事情。我只是不确定如何获取它以便它在两个事件之间分离,因此我可以使滚动数字动画触发并停止而不会干扰其他滚动标题脚本。

javascript jquery html scroll
2个回答
0
投票

您可以命名空间事件,这些事件允许您仅使用off()删除该命名空间并保留相同类型的其他事件侦听器

尝试类似的东西:

var reset = function reset() {
  console.log($(this).scrollTop())
  if ($(this).scrollTop() > 1300) {
    fx()
    $(this).off("scroll.myScrollName");
  }
};

$(window).on("scroll.myScrollName", reset);

0
投票

jQuery的off方法接受一个已经附加了on的函数,因此你只能“关闭”那个回调而不是全部。

http://api.jquery.com/off/

我不知道你怎么能在里面引用这个函数,作为一种解决方法,我会做类似......

var reset = function() {
  //your_code...
  offReset(this);
}

var offReset = function(element) {
  $(element).off(reset)
}
© www.soinside.com 2019 - 2024. All rights reserved.