js动画
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <title>Document</title> <style> #block { position: absolute; width: 100px; height: 100px; background-color: red; top: 0; left: 0; } </style> </head> <body> <div id="block"></div> <script type="text/javascript"> window.onload = function () { // API实现 const requestAnimationFrameHandle = () => { const element = document.getElementById('block'); let start = null; let animate = null; const step = timestamp => { if (!start) start = timestamp; const progress = timestamp - start; element.style.left = Math.min(progress / 10, 500) + 'px'; if (progress < 5000) { animate = window.requestAnimationFrame(step); } else { window.cancelAnimationFrame(animate); } }; animate = window.requestAnimationFrame(step); }; requestAnimationFrameHandle(); // 定时器实现 const timeAnimation = () => { const element = document.getElementById('block'); let progress = 0; let timer = setInterval(() => { element.style.left = Math.min(progress / 10, 500) + 'px'; progress = progress + 10; if (progress > 5000) { clearInterval(timer); timer = null; } }, 10); }; timeAnimation(); }; </script> </body> </html>
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】凌霞软件回馈社区,博客园 & 1Panel & Halo 联合会员上线
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】博客园社区专享云产品让利特惠,阿里云新客6.5折上折
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步