2017-08-08 63 views
1

我希望数值达到指定值并停留在那里,但是因为每当页面滚动到某个高度以下时都会调用该函数,它会回到1.jQuery - 在某个滚动位置后停止/取消滚动事件回调

解决方法是只在页面滚动到某个高度以下时才调用该函数一次。

我用尽放置.one()方法好几个地方,但没有帮助

http://jsfiddle.net/d7vKd/1543/

$(document).on('scroll', function() { 
    if ($(this).scrollTop() >= $("#mydiv").position().top) { 
    window.randomize = function() { 
     $('.radial-progress1').attr('data-progress', Math.floor(94)); 
    }; 
    $('.count').each(function() { 
     $(this).prop('Counter', 0).animate({ 
     Counter: $(this).text() 
     }, { 
     duration: 6000, 
     easing: 'swing', 
     step: function(now) { 
      $(this).text(Math.ceil(now)); 
     } 
     }); 
    }); 
    setTimeout(window.randomize, 200); 
    } 
}) 
+0

当你的触发器满足时,你是否考虑过$(document).off(“scroll”)? –

+0

查看[我的回答](https://stackoverflow.com/a/23685237/104380)有关调用函数一次 – vsync

+0

$(document).off(“scroll”)冲突,因为我在我的网站上有另一个滚动功能(隐藏/显示标题导航)。你知道另一个解决方案 – Vegapunk

回答

1

你应该unbindscroll事件一旦回调已满足其要求:

$(document).on('scroll.someName', function(){ 
    var isPassedPos = $(this).scrollTop() >= $("#mydiv").position().top; 

    if(isPassedPos){ 
    $(document).off('scroll.someName') // <-------------- remove the event listener 

    window.randomize = function() { 
     $('.radial-progress1').attr('data-progress', Math.floor(94)); 
    }; 

    $('.count').each(function() { 
     $(this).prop('Counter', 0).animate({ 
     Counter: $(this).text() 
     }, { 
     duration: 6000, 
     easing: 'swing', 
     step: function(now) { 
      $(this).text(Math.ceil(now)); 
     } 
     }); 
    }); 

    setTimeout(window.randomize, 200); 
    } 
}) 
+0

谢谢我学到了新东西! – Vegapunk

+0

噢,不,解决方案带来了另一个问题,您的解决方案可以以某种方式隔离吗?因为我有另一个$(document).scroll(function(){在我的网站上,现在被破坏:) – Vegapunk

+0

$(document).scroll(function(){ if($(this).scrollTop()> 400) {“topnav”)。removeClass(“transp”).addClass('wtbck'); } else {(“#topnav”)。removeClass(“wtbck”).addClass('transp') ; } }); – Vegapunk