气死了 一个破题 写了一个半小时
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Document</title> <style> body { margin: 0px; } #box1 { width: 100px; height: 100px; background-color: red; position: absolute; left: 0px; top: 50px; /*margin-left: 8px;*/ } #box2 { width: 100px; height: 100px; background-color: blue; position: absolute; left: 0px; top: 180px; } </style> </head> <body> <input type="button" name="" value='button1' id='btn1'> <input type="button" name="" value='buttom2' id='btn2'> <div id='box1'></div> <div id='box2'></div> <script> var box = document.getElementById('box1'); var btn1 = document.getElementById('btn1'); var btn2 = document.getElementById('btn2'); btn1.onclick = function() { animation(box1,200); animation(box2,200); } btn2.onclick = function() { animation(box1,800); animation(box2,800); } function animation(element,target) { var step = 10; if (element.timeId) { clearInterval(element.timeId); element.timeId = null; } if (element.offsetLeft >= target) { step = -(Math.abs(step)); console.log(step); } element.timeId = setInterval(function() { if (Math.abs(element.offsetLeft - target) <= Math.abs(step)) { element.style.left = target + 'px'; }else { element.style.left = element.offsetLeft + step + 'px'; } },30); } </script> </body> </html>
运行结果: