简体   繁体   English

jQuery-在视口中出现时对数字进行动画处理

[英]jQuery - Animate numbers when appears in viewport

I'm currently trying to animate some numbers when the user scroll and the DIV appears in the viewport. 当用户滚动并且DIV出现在视口中时,我目前正在尝试为一些数字设置动画。 Like that: http://www.dimfolio.fr/ 像这样: http : //www.dimfolio.fr/

On the example it looks to be CSS3, for some reasons I'd prefer to use jQuery. 在该示例中,它看起来是CSS3,出于某些原因, 我更喜欢使用jQuery。

Currently, I use " animateNumber " plugin and this function to check if the div appears in the viewport: 当前,我使用“ animateNumber ”插件和此函数来检查div是否出现在视口中:

$.fn.is_on_screen = function(){

var win = $(window);

var viewport = {
    top : win.scrollTop(),
    left : win.scrollLeft()
};
viewport.right = viewport.left + win.width();
viewport.bottom = viewport.top + win.height();

var bounds = this.offset();
bounds.right = bounds.left + this.outerWidth();
bounds.bottom = bounds.top + this.outerHeight();

return (!(viewport.right < bounds.left || viewport.left > bounds.right || viewport.bottom < bounds.top || viewport.top > bounds.bottom));

};

Here is my code: 这是我的代码:

JS: JS:

function animate_stats() {
  $('.stats_number').each(function() {
     if(!$(this).hasClass("numbered")) {
        var thisnumber = $(this).attr('title');
        $(this).animateNumber({ number: thisnumber }, 3000, function() {
            $(this).addClass('numbered');
        });
     }
  });
};

if( $('#statistics').is_on_screen() ) {
  animate_stats();
}

$(window).scroll(function(){
  if( $('#statistics').is_on_screen() ) {
     animate_stats();
  }
});

HTML: HTML:

<a href="#" class="stat">
   <div class="stats_number" title="79">0</div>
   <br />
   My title
</a>

The problem is that the number animation repeats and repeats again when the div appears. 问题是数字动画会重复并在div出现时再次重复。 Of course I'd like the animation to run only once. 当然, 我希望动画只运行一次。

I suppose that the issue comes from my utilisation of "each" function but note sure. 我认为问题出在我对“每个”功能的利用上,但是请注意。

Anyone can help? 有人可以帮忙吗? Thank you very much! 非常感谢你!

After the animation is run, remove the listener. 运行动画后,删除侦听器。

$(window).on('scroll.animateStats', function(){
  if( $('#statistics').is_on_screen() ) {
     animate_stats();
     $(window).off('scroll.animateStats');
  }
});

I namespaced the scroll event so that when we remove it we're only removing this event handler, and not all scroll handlers. 我为滚动事件命名空间,以便在删除滚动事件时仅删除此事件处理程序,而不是所有滚动处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM