<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width,height=device-height,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0,user-scalable=no,viewport-fit=cover"> <title>動畫函數</title> <style> * { margin: 0; padding: 0; } #box { width: 100px; height: 100px; background: red; position: absolute; top: 60px; left: 0; } </style></head><body> <button id="btn1">滑動到400px</button> <button id="btn2">滑動到800px</button> <div id="box"></div> <script> var btn1 = document.querySelector('#btn1'); var btn2 = document.querySelector('#btn2'); var box = document.querySelector('#box'); btn1.addEventListener('click', function () { animate(box, 400); }); btn2.addEventListener('click', function () { animate(box, 800); }); //封裝動畫函數 function animate(obj, target) { clearInterval(obj.timerId); obj.timerId = setInterval(function () { var step = 9; var current = obj.offsetLeft; step = current < target ? step : -step; current = current + step; if (Math.abs(target - current) > Math.abs(step)) { obj.style.left = current + 'px'; }else { obj.style.left = target + 'px'; clearInterval(obj.timerId); } }, 30) } </script></body></html>