jQuery 动画数字计数器从零到值 [英] jQuery animated number counter from zero to value
问题描述
我创建了一个脚本,用于将数字从零到其值进行动画处理.
I have created a script to animate a number from zero to it's value.
jQuery
$({ Counter: 0 }).animate({
Counter: $('.Single').text()
}, {
duration: 1000,
easing: 'swing',
step: function() {
$('.Single').text(Math.ceil(this.Counter));
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="Single">150</span>
我现在想为每个匹配的类在页面上多次运行脚本.
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));
}
});
});
推荐答案
你的 this
没有引用 step 回调中的元素,而是你想在开头保留对它的引用你的函数(在我的例子中被包裹在 $this
中):
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));
}
});
});
更新:如果您想显示十进制数,那么您可以使用 舍入到 2 位小数,而不是使用
:Math.ceil
对值进行四舍五入value.toFixed(2)
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屋!