代码
<!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> * { margin: 0; padding: 0; } #box { width: 100px; height: 100px; background: darkmagenta; position: absolute; left: 0; top: 30px; } </style> </head> <body> <button id='right'>向右走</button> <button id='left'>向左走</button> <div id="box"></div> <script> var right = document.getElementById('right'); var left = document.getElementById('left'); var box = document.getElementById('box'); var timer = null; // 向右走 right.onclick = function () { run(box,'left',5,500) } // 向左走 left.onclick = function () { run(box,'left',10,0) } function run(ele,attr,step,target) { step = target>parseInt(getStyle(ele, attr))? step :-step; // if( target>parseInt(getStyle(ele, attr))){ // step = step; // }else{ // step = -step; // } clearInterval(timer); timer = setInterval(function () { var dis = parseInt(getStyle(ele, attr)) + step; if (dis <= target && step < 0 || dis >= target && step > 0) { dis = target; clearInterval(timer); } ele.style[attr] = dis + 'px'; }, 50) } // 获取元素样式 function getStyle(ele, attr) { if (window.getComputedStyle) { return getComputedStyle(ele)[attr]; } else { return ele.currentStyle[attr]; } } </script> </body> </html>