<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> div { position: absolute; left: 0; width: 100px; height: 100px; background-color: pink; } span { position: absolute; left: 0; top: 200px; display: block; width: 150px; height: 150px; background-color: purple; } </style> </head> <body> <button class="btn500">点击到500</button> <button class="btn800">点击到800</button> <span></span> <script> function animate(obj, target, callback) { clearInterval(obj.timer); obj.timer = setInterval(function() { var step = (target - obj.offsetLeft) / 10; step = step > 0 ? Math.ceil(step) : Math.floor(step); if (obj.offsetLeft == target) { clearInterval(obj.timer); if (callback) { callback(); } } obj.style.left = obj.offsetLeft + step + 'px'; }, 15); } var span = document.querySelector('span'); var btn500 = document.querySelector('.btn500'); var btn800 = document.querySelector('.btn800'); btn500.addEventListener('click', function() { animate(span, 500, function() { span.style.backgroundColor = 'green'; }); }) btn800.addEventListener('click', function() { animate(span, 800, function() { span.style.backgroundColor = 'red'; }); }) </script> </body> </html>