简单的jquery计数器出现 [英] Simple jquery counter on appear
问题描述
我不确定有许多不同的计数器脚本,从何处开始,什么是过大的,什么不是.
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)
这个想法是,要使元素滚动到视图中时要对其进行动画/计数,我要做的就是给它一个counter
类.
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
.
例如,html将是:
<span class="counter">99</span><span class="counter">55</span>
首先,将那些元素设置为visibility:hidden
,直到滚动到视图中.然后,它们将从0增加到文本节点的值(在这种情况下为99和55),并在达到该值时停止.某种缓和效果可能是理想的,但不是必须的(例如,在达到该值时快速启动并放慢速度)
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.
推荐答案
这是您所需的完整代码:
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);
}
isElementVisible
功能帮助您确定是否在每次滚动后都在屏幕上显示控件.
The isElementVisible
function help to find out is a control is appeared on the screen after every scroll or not.
然后在每次滚动时调用此函数,如果显示.counter
元素,则仅使用startTimer
函数为此元素启动计时器.
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.
!$(this).hasClass('Starting')
已添加到代码中,以防止不必要的调用功能,这是在以前启动计时器并一次又一次滚动滚动计时器时启动的.
第一次启动计时器时,Starting
类将添加到元素中,并在下一次被跳过.
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示例
>>> JSFiddle Sample
您可以看到每个计时器仅在看到时启动,而其他计数器只有在看到时才启动.
You can see that every timer start only when is seen and other counters don't start until those are seen too.
这篇关于简单的jquery计数器出现的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!