[英]jQuery - Animate numbers when appears in viewport
當用戶滾動並且DIV出現在視口中時,我目前正在嘗試為一些數字設置動畫。 像這樣: http : //www.dimfolio.fr/
在該示例中,它看起來是CSS3,出於某些原因, 我更喜歡使用jQuery。
當前,我使用“ 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));
};
這是我的代碼:
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:
<a href="#" class="stat">
<div class="stats_number" title="79">0</div>
<br />
My title
</a>
問題是數字動畫會重復並在div出現時再次重復。 當然, 我希望動畫只運行一次。
我認為問題出在我對“每個”功能的利用上,但是請注意。
有人可以幫忙嗎? 非常感謝你!
運行動畫后,刪除偵聽器。
$(window).on('scroll.animateStats', function(){
if( $('#statistics').is_on_screen() ) {
animate_stats();
$(window).off('scroll.animateStats');
}
});
我為滾動事件命名空間,以便在刪除滾動事件時僅刪除此事件處理程序,而不是所有滾動處理程序。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.