JS实现匀速动画

it2023-09-29  68

JS实现匀速动画

<style> .box1 { width: 200px; height: 200px; background-color: #2aabd2; position: absolute; } </style> <!--按钮--> <button class="bt1">匀速</button> <!--一个盒子--> <div class="box1"></div> var box1 = document.querySelector(".box1"); var bt1 = document.querySelector(".bt1"); // 匀速 // 点击盒子移动 bt1.onclick = function () { animation1(box1,500); }; function animation1(ele1,target1) { clearInterval(ele1.timer); // 走5像素 var step1 = (target1 - ele1.offsetLeft) > 0 ? 5 : -5; ele1.timer = setInterval(function () { ele1.style.left = ele1.offsetLeft + step1 + "px"; // 判断剩余距离是否小于规定像素 if (Math.abs(target1 - ele1.offsetLeft) < Math.abs(step1)){ // 直接到达目标位置## 标题 ele1.style.left = target1 + "px"; clearInterval(ele1.timer); } },10) } ```## JS实现匀速动画
最新回复(0)