<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> div { position: absolute; width: 200px; height: 200px; background-color: pink; } span { position: absolute; left: 0; top: 200px; display: block; width: 150px; height: 150px; background-color: plum; } </style> </head> <body> <div></div> <span>111</span> <script> // var obj = {}; // obj.name = 'andy' // 简单动画函数封装obj目标对象,target目标位置 // 给不同的元素指定不同的定时器 function animate(obj, target) { obj.timer = setInterval(function () { if (obj.offsetLeft >= target) { // 停止动画 clearInterval(obj.timer); } obj.style.left = obj.offsetLeft + 1 + 'px'; }, 30) } var div = document.querySelector('div') var span = document.querySelector('span') // 调用函数 animate(div, 300); animate(span, 200); </script> </body> </html>