<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>Document</title> <style> body, html, div, * { margin: 0; padding: 0; } div { height: 150px; width: 150px; background: plum; position: absolute; top: 0; left: 0; } span { display: block; width: 100px; height: 100px; background: powderblue; position: absolute; top: 200px; left: 0; } </style> </head> <body> <div>会动的盒子</div> <span>小盒子</span> <script> var div = document.querySelector(‘div‘); var span = document.querySelector(‘span‘); var start = setInterval(function() { if (div.offsetLeft >= 300) { clearInterval(start); } div.style.left = div.offsetLeft + 2 + ‘px‘; }, 10); // 页面中不止有一个动画,所以可以给动画封装一个函数 // 简单动画函数封装 有两个参数 obj目标对象 target目标位置 function animate(obj, target) { var start = setInterval(function() { if (obj.offsetLeft >= target) { clearInterval(start); } obj.style.left = obj.offsetLeft + 2 + ‘px‘; }, 10); } // 调用函数 animate(span, 200); </script> </body> </html>
原文:https://www.cnblogs.com/qtbb/p/11707462.html