🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
## 1.[JS动画原理](https://gitee.com/html5_of_the_buddha_department/specialEffect/tree/master/javascript/JS%E5%8A%A8%E7%94%BB) 实现一个简单动画 ~~~ //csss #test{ position:absolute; width:100px; height:100px; background:red; left:50px; } //html <div id="test"></div> <button id="btn">btn</button> //js var btn = document.getElementById("btn"); var test = document.getElementById("test"); var timer; btn.onclick = function () { timer = setInterval(function () { if(test.offsetLeft == 300){ clearInterval(timer) }else{ test.style.left = test.offsetLeft+10+"px"; } },100) ~~~ ~~~ 1. 多次点击btn会有一个明显的加速效果,因为每点击一次,开一个定时器 解决方案:在开启定时器之前,先清除定时器,代码如下 btn.onclick = function () { clearInterval(timer); timer = setInterval(function () { var speed = 1; if(test.offsetLeft >=300){ clearInterval(timer) }else{ test.style.left = test.offsetLeft+speed+"px"; } },30) } ~~~ ~~~ 动画要点 If——else 进入动画,获取说开启定时器之前先清除定时器 ~~~ //推荐使用setTimeout这样不用考虑关闭定时器 ~~~ var btn = document.getElementById("btn"); var test = document.getElementById("test"); var timer; btn.onclick = function () { function go(){ if(test.offsetLeft<100){ test.style.left = test.offsetLeft+10+"px"; setTimeout(go,30) } } go(); } ~~~ ## 2.[轮播](https://gitee.com/html5_of_the_buddha_department/specialEffect/tree/master/javascript/%E7%84%A6%E7%82%B9%E5%9B%BE%E8%BD%AE%E6%92%AD%E6%95%88%E6%9E%9C) [在线演示](https://html5_of_the_buddha_department.gitee.io/banner-lunbo/) //推荐使用setTimeout(),这样不用考虑关闭定时器