下面的代码按您的要求执行。
它检查
.count
元素在页面加载和滚动后都可见。它使用类
.nonVisible
为了帮助确定计数器是否刚刚进入视图或离开,这样我们可以适当地停止动画。
如果在元素滚动出视图时不停止动画,则动画将继续运行,如果元素返回视图,则不会再次启动,而是继续原始动画。
同样,将计数器移出视图后的文本设置为“0”,意味着用户在计数器重新启动前不会短暂看到前面的数字。
下面的代码是完全注释的。
演示
// Add event on document ready
$(document).ready(function() {
// Add event on document scroll
$(window).scroll(function() {
// Cycle through each counter
$(".count").each(function() {
// Check if counter is visible
if ($(this).isOnScreen()) {
// Start counter
startCounter($(this));
} else {
// Check if it has only just become non-visible
if ($(this).hasClass("notVisible") == false) {
// Stop animation
$(this).stop();
// Add nonVisible class
$(this).addClass("notVisible");
// This stops the user very briefly seeing the previous number before the counter restarts
$(this).text("0");
}
}
});
});
});
// Check if an element is on screen
// Thanks to Adjit - taken from the url below
// Reference : https://stackoverflow.com/questions/23222131/jquery-fire-action-when-element-is-in-view#answer-23222523
$.fn.isOnScreen = 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));
};
//Run counter, separate function so we can call it from multiple places
function startCounter(counterElement) {
// Check if it has only just become visible on this scroll
if (counterElement.hasClass("notVisible")) {
// Remove notVisible class
counterElement.removeClass("notVisible");
// Run your counter animation
counterElement.prop('Counter', 0).animate({
Counter: counterElement.attr("counter-lim")
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
counterElement.text(Math.ceil(now).toLocaleString());
}
});
}
}
// On page load check if counter is visible
$('.count').each(function() {
// Add notVisible class to all counters
// It is removed within startCounter()
$(this).addClass("notVisible");
// Check if element is visible on page load
if ($(this).isOnScreen() === true) {
// If visible, start counter
startCounter($(this));
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div><span class="count" counter-lim="123000"></span></div>
<div style="margin-bottom: 500px;">Scroll down to see the counter</div>
<div><span class="count" counter-lim="123000"></span></div>
<div><span class="count" counter-lim="350000"></span></div>
<div><span class="count" counter-lim="50000"></span></div>