我试图让这个 jQuery 动画计数器在用户向下滚动页面超过 200 像素时立即触发:
原始 jQuery 代码来自 here
$('.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));
}
});
});
我尝试将其包装在以下 jQuery 中,但它直到最后才触发动画:
$(window).scroll(function() {
if ($(window).scrollTop() > 200) {
$('.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));
}
});
});
}
});
HTML:
<span class="Count">100</span>
<br/>
<span class="Count">200</span>
<br/>
<span class="Count">300</span>
另一篇文章中的 fiddle 是 here
当用户滚动到 View 中或页面向下 200 像素时触发 jQuery 计数器的最佳方法是什么?我也尝试过 jQuery Wayfinder,但没有成功。
最佳答案
在触发动画之前解除滚动处理程序的绑定(bind)(使用 $(window).off("scroll")
),以防止用户继续滚动时动画重新启动。
$(window).scroll(startCounter);
function startCounter() {
if ($(window).scrollTop() > 200) {
$(window).off("scroll", startCounter);
$('.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));
}
});
});
}
}
body {
font-family: sans-serif;
height: 300vh;
}
.Count {
position: fixed;
top: 8px;
left: 8px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="Count">100</div>
关于javascript - 在窗口滚动时触发 jQuery 动画数字计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29858421/