Dre*_*TeK 36 html javascript each jquery animation
我创建了一个脚本来动画从零到它的值的数字.
jQuery的
$({ Counter: 0 }).animate({
Counter: $('.Single').text()
}, {
duration: 1000,
easing: 'swing',
step: function() {
$('.Single').text(Math.ceil(this.Counter));
}
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span class="Single">150</span>
Run Code Online (Sandbox Code Playgroud)
我现在想在页面上为每个匹配的类多次运行该脚本.
以下是我正在尝试但到目前为止没有成功:
HTML
<span class="Count">200</span>
<span class="Count">55</span>
Run Code Online (Sandbox Code Playgroud)
JQUERY
$('.Count').each(function () {
jQuery({ Counter: 0 }).animate({ Counter: $(this).text() }, {
duration: 1000,
easing: 'swing',
step: function () {
$(this).text(Math.ceil(this.Counter));
}
});
});
Run Code Online (Sandbox Code Playgroud)
flo*_*bon 74
您this
没有引用步骤回调中的元素,而是希望在函数开头保留对它的引用($this
在我的示例中包含):
$('.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));
}
});
});
Run Code Online (Sandbox Code Playgroud)
更新:如果要显示十进制数字,则Math.ceil
可以使用最多2位小数来舍入该值而不是舍入,例如value.toFixed(2)
:
step: function () {
$this.text(this.Counter.toFixed(2));
}
Run Code Online (Sandbox Code Playgroud)
ade*_*neo 17
this
步骤内部回调不是元素,而是传递给animate()的对象
$('.Count').each(function (_, self) {
jQuery({
Counter: 0
}).animate({
Counter: $(self).text()
}, {
duration: 1000,
easing: 'swing',
step: function () {
$(self).text(Math.ceil(this.Counter));
}
});
});
Run Code Online (Sandbox Code Playgroud)
另一种方式来做到这一点,并保持引用this
会
$('.Count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Run Code Online (Sandbox Code Playgroud)
重要提示:这似乎是一个小差异,但您应该使用数据属性来保持原始数字最多.更改原始号码可能会产生意想不到的后果.例如,每次元素进入屏幕时我都会运行此动画.但是,如果元素进入,退出,然后在第一个动画结束前第二次进入屏幕,它将计入错误的数字.
HTML:
<p class="count" data-value="200" >200</p>
<p class="count" data-value="70" >70</p>
<p class="count" data-value="32" >32</p>
Run Code Online (Sandbox Code Playgroud)
JQuery的:
$('.count').each(function () {
$(this).prop('Counter', 0).animate({
Counter: $(this).data('value')
}, {
duration: 1000,
easing: 'swing',
step: function (now) {
$(this).text(this.Counter.toFixed(2));
}
});
});
Run Code Online (Sandbox Code Playgroud)
代码的作用是,数字 8000 从 0 计数到 8000。问题是,它被放置在相当长的页面中间,一旦用户向下滚动并实际看到数字,动画就已经结束了。我想在计数器出现在视口中时触发它。
JS:
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
Run Code Online (Sandbox Code Playgroud)
和 HTML:
<span class="count">8000</span>
Run Code Online (Sandbox Code Playgroud)