Home > Article > Web Front-end > What is the source code for js easing animation encapsulation? (code example)
The content of this article is about what is the source code of js easing animation encapsulation? (Code example) has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Mainly used offsetLeft, Math.ceil, Math.floor, Math.abs.
Note that the value obtained by offsetLeft is the rounded value of style.left, offsetLeft = Math.round (the numerical part of style.left), for example, style.left = 369.4px, the obtained offsetLeft = 369.
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>缓动动画</title> <style> #slow_action { width: 100px; height: 100px; background: pink; position: absolute; } </style> </head> <body> <button id="btn1">运动到400</button> <button id="btn2">运动到0</button> <p id="slow_action"></p> </body> <script> var btn1 = document.getElementById("btn1") var btn2 = document.getElementById("btn2") var p = document.getElementById("slow_action") /** * 动画原理 = 盒子位置 + 步长(步长越来越小) * 盒子位置 = 盒子本身的位置 + (目标位置 - 盒子本身位置)/10 */ btn1.onclick = function () { fn(p,400) } btn2.onclick = function () { fn(p,0) } function fn(ele, target) { clearInterval(ele.timer); ele.timer = setInterval(function () { // var target = 400; //最后10像素都是1px向目标位置移动 最后到达指定位置 var step = (target - ele.offsetLeft)/10; //差值大于10的时候向上取整 小于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> </html>
The above is what is the source code for encapsulating js easing animation? (Code examples) full introduction, if you want to know more about JavaScript video tutorial, please pay attention to the PHP Chinese website.
The above is the detailed content of What is the source code for js easing animation encapsulation? (code example). For more information, please follow other related articles on the PHP Chinese website!