javascript - Javascript:在滚动上做动画
问题描述
我有简单的代码,当页面加载时动画开始。当我在这个 div 上滚动时,是否有任何选项如何开始动画?
$('.count').each(function () {
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 3000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="shiva"><span class="count">200</span></div>
解决方案
使用 onscroll 事件计算窗口和元素之间的距离:
$(window).on('scroll',function () {
$('.count').each(function () {
var wst=$(window).scrollTop();
var wh=$(window).height();
var dot=$(this).offset().top;
var dh=$(this).height();
if((dot-wst>0)&&(dot-wst<=wh-dh)&&(!$(this).hasClass("animate-complete"))){
$(this).addClass("animate-complete");
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 3000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<br>
<div id="shiva"><span class="count">200</span></div>
推荐阅读
- node.js - Firebase 实时数据库触发器:什么时候异步,什么时候不异步
- c# - 找到由两个 3 位数字的乘积构成的最大回文 C#
- java - Java Vert.x 反向代理自动 Netty 解码
- python - 如何在散景中为曲线下的区域着色?
- javascript - RxJs6 - 静态合并一个可观察的数组
- android-source - 预安装一些应用程序,以便用户无需 root 即可卸载它们
- xamarin.forms - 带有标签条目的自定义内容视图重复 Xamarin 表单
- javascript - 更简单的数据过滤方法
- python-3.x - 在 python3 中将解析的文本写入 .csv 文件时出现换行符/换行符问题
- ruby-on-rails - 无法安装“Mysql2”版本 0.5.2