1 function animate(obj, target, callback) { 2 clearInterval(obj.timer) 3 obj.timer = setInterval(function () { 4 // 把移动值改为整数避免存在小数 5 var step = (target - obj.offsetLeft) / 10; 6 step = step > 0 ? Math.ceil(step) : Math.floor(step); 7 if (obj.offsetLeft == target) { 8 clearInterval(obj.timer) 9 // 回调函数写在定时器结束后面 10 if (callback) { 11 callback(); 12 } 13 } 14 // 把里面的移动值改为慢慢变小的值 15 obj.style.left = obj.offsetLeft + step + ‘px‘ 16 }, 15) 17 } 18 animate(div, 700) 19 btn1.addEventListener(‘click‘, function () { 20 // 当我们不断地点击按钮就会开启越来越多的定时器 21 animate(box, 700) 22 }) 23 btn2.addEventListener(‘click‘, function () { 24 // 当我们不断地点击按钮就会开启越来越多的定时器 25 animate(box, 900, function () { 26 box.style.backgroundColor = ‘red‘; 27 28 }) 29 })
原文:https://www.cnblogs.com/xf2764/p/12702964.html