js缓动动画及其封装
2016-11-20 17:43
176 查看
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> <style> div { width: 100px; height: 100px; background-color: pink; position: absolute; left: 0; } </style> </head> <body> <button>运动到200</button> <button>运动到400</button> <div></div> <script> //----------------------------js缓动动画---------------------------- var btn = document.getElementsByTagName("button"); var div = document.getElementsByTagName("div")[0]; btn[0].onclick = function () { animate(div,200); } btn[1].onclick = function () { animate(div,400); } //缓动动画封装 function animate(ele,target) { //要用定时器,先清定时器 //一个萝卜一个坑儿,一个元素对应一个定时器 clearInterval(ele.timer); //定义定时器 ele.timer = setInterval(function () { //获取步长 //步长应该是越来越小的,缓动的算法。 var step = (target-ele.offsetLeft)/10; //对步长进行二次加工(大于0向上取整,小于0项下取整) step = step>0?Math.ceil(step):Math.floor(step); //动画原理: 目标位置 = 当前位置 + 步长 ele.style.left = ele.offsetLeft + step + "px"; //检测缓动动画有没有停止 console.log(1); if(Math.abs(target-ele.offsetLeft)<=Math.abs(step)){ //处理小数赋值 ele.style.left = target + "px"; clearInterval(ele.timer); } },30); } </script> </body> </html>
相关文章推荐
- js-匀速/缓动动画-简单封装
- js 匀速/缓动动画 简单封装
- JS封装缓动动画函数
- js实现图片旋转动画的封装
- JS简单动画封装浅析
- js缓动框架(封装)
- 动画封装三:单条样式的缓动运动
- 动画封装四:用json实现多条样式的缓动运动
- TweenLite动画引擎JS缓动简单版效果分享
- 分享一个即插即用的私藏缓动动画JS小算法
- 缓动动画原理--封装基本函数
- js动画基本原理和简单封装
- window.requestAnimationFrame与Tween.js配合使用实现动画缓动效果
- JS简单动画封装
- JS轮播图中缓动函数的封装
- JS —— 轮播图中的缓动函数的封装
- animate动画方法封装:原生JS实现
- js 动画封装
- 动画封装二:实现水平缓动运动
- JS基础知识——缓动动画