如何在不满足条件时关闭滚动事件& LISTEN在满足条件时重新开启?

时间:2017-03-14 10:16:01

标签: javascript jquery events scroll event-handling

我想只在必要时收听/关闭滚动事件。至于现在,每次off事件,它都不会收听on。作为下面代码的一个例子,我希望在条件不满足时关闭滚动事件,然后在满足条件时重新开启。



$(window).on('scroll', '[data-apple]', function() {
  const scroll = $(window).scrollTop();
  const height = $('[data-apple]').outerHeight();
  const offset = 52;
        
  if (scroll > offset && scroll < height + offset){
    // Listen to scroll
    console.log('listen');
  } else {
    // Stop listening to scroll
    $(window).off('scroll', '[data-apple]');
  }
  
});
&#13;
body { background: wheat; min-height: 2000px; }
.apple { height: 200px; background: red; }
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div data-apple class="apple">
</div>
&#13;
&#13;
&#13;

0 个答案:

没有答案