问题
There are so many different counter scripts I'm not sure where to start, what's overkill and what's not.
I'm looking for a simple counter script that fires when the target element first appears into view onscreen (for example, does not fire until scrolled into view)
The idea is that all I have to do to get the element to animate/count when scrolled into view, is give it a class of counter
.
For example, html will be:
<span class="counter">99</span><span class="counter">55</span>
First, those elements would be set to visibility:hidden
until scrolled into view. Then, they would increment from 0 to the value of the text node (99 and 55 in this case) and stop when they reach the value. Some sort of ease out effect may be desirable but isn't a must (for example, start fast and slow down as it reaches the value)
Thanks in advance. Just looking for the simplest solution.
回答1:
This is a complete code for your purpose:
function isElementVisible($elementToBeChecked)
{
var TopView = $(window).scrollTop();
var BotView = TopView + $(window).height();
var TopElement = $elementToBeChecked.offset().top;
var BotElement = TopElement + $elementToBeChecked.height();
return ((BotElement <= BotView) && (TopElement >= TopView));
}
$(window).scroll(function () {
$( ".counter" ).each(function() {
isOnView = isElementVisible($(this));
if(isOnView && !$(this).hasClass('Starting')){
$(this).addClass('Starting');
startTimer($(this));
}
});
});
function startTimer($this) {
setTimeout(function(){
$this.html($this.html() - 1);
startTimer($this);
}, 1000);
}
The isElementVisible
function help to find out is a control is appeared on the screen after every scroll or not.
Then you call this function of every scroll and if a .counter
element appear on display, then start timer ONLY for THIS element using the startTimer
function.
The !$(this).hasClass('Starting')
is added to code to prevent unwanted call function, when a timer is started before and scroll on it again and again.
When a timer start for first time, the Starting
class is added to element and is skipped in next times.
>>> JSFiddle Sample
You can see that every timer start only when is seen and other counters don't start until those are seen too.
回答2:
Looks like part of your question already has an answer: Start executing jQuery function when I scroll to a specific <div>
The answer on that question has a jsfiddle that will get you started. It's a matter of writing a simple counter script in start_count
来源:https://stackoverflow.com/questions/25105412/simple-jquery-counter-on-appear