jQuery的动画数量计数器从零到值 [英] jQuery animated number counter from zero to value
问题描述
我创建了一个脚本,从零动画一个数字,它的价值。
工作
HTML
<跨度类=单> 150℃/ SPAN>
JQUERY
的jQuery({计数器:0})。动画({计数器:'单'$()文字()},{
时间:1000,
宽松:'摇摆',
步骤:函数(){
$('单')文本(Math.ceil(this.Counter))。
}
});
不工作
我现在要运行的网页上的脚本多次为每个匹配的类。
下面是我想做但没有成功至今:
HTML
<跨度类=计数> 200℃/ SPAN>
&所述;跨度类=计数> 55℃; /跨度>
JQUERY
$('伯爵')。每个(函数(){
jQuery的({计数器:0})。动画({计数器:$(本)的.text()},{
时间:1000,
宽松:'摇摆',
步骤:函数(){
$(本)的.text(Math.ceil(this.Counter));
}
});
});
您这个
并不是指在步骤回调的元素,而不是你要保持一个在你的函数的开头提到它(包裹在 $这种
在我的例子):
$('伯爵')。每个(函数(){
变量$此= $(本);
jQuery的({计数器:0})。动画({计数器:$ this.text()},{
时间:1000,
宽松:'摇摆',
步骤:函数(){
$ this.text(Math.ceil(this.Counter));
}
});
});
更新:如果你想显示十进制数,然后四舍五入,而不是用 Math.ceil
值可以四舍五入到2位小数例如用 value.toFixed(2)
:
步:功能(){
$ this.text(this.Counter.toFixed(2));
}
I have created a script to animate a number from zero to it's value.
Working
HTML
<span class="Single">150</span>
JQUERY
jQuery({ Counter: 0 }).animate({ Counter: $('.Single').text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$('.Single').text(Math.ceil(this.Counter));
}
});
Not Working
I now want to run the script several times on the page for each matching class.
Below is what I am trying but with no success so far:
HTML
<span class="Count">200</span>
<span class="Count">55</span>
JQUERY
$('.Count').each(function () {
jQuery({ Counter: 0 }).animate({ Counter: $(this).text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$(this).text(Math.ceil(this.Counter));
}
});
});
Your this
doesn't refer to the element in the step callback, instead you want to keep a reference to it at the beginning of your function (wrapped in $this
in my example):
$('.Count').each(function () {
var $this = $(this);
jQuery({ Counter: 0 }).animate({ Counter: $this.text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$this.text(Math.ceil(this.Counter));
}
});
});
Update: If you want to display decimal numbers, then instead of rounding the value with Math.ceil
you can round up to 2 decimals for instance with value.toFixed(2)
:
step: function () {
$this.text(this.Counter.toFixed(2));
}
这篇关于jQuery的动画数量计数器从零到值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!