效果
盒子不是匀速移动的,而是由快到慢,缓缓停下,看起来比较顺滑。
核心代码
<script>
var div = document.querySelector('div');
var span = document.querySelector('span');
var btn1 = document.querySelector('.button1');
var btn2 = document.querySelector('.button2');
function move(obj, target, callback) { //callback是回调参数(见后面
// 清除多次点击后的定时器,保留最新的那一次
clearInterval(obj.timer);
// 使用obj.timer,把timer当作obj的属性,如果使用var timer = ,调用一次就会开辟一次内存空间
obj.timer = setInterval(function () {
//对步长向上取整,因为除以10可能有小数
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);
}
//2.调用函数
move(div, 300);
btn1.addEventListener('click', function () {
move(span, 500);
})
btn2.addEventListener('click', function () {
move(span, 800, function () { //第三个是回调函数,把盒子颜色变红
span.style.backgroundColor = 'red';
});
})
// 当我们不断的点击按钮,这个元素的速度会越来越快,因为开启了太多的定时器
// 解决方案就是 让我们元素只有一个定时器执行
// 先清除以前的定时器,只保留当前的一个定时器执行
</script>
</body>
框架
<button class="button1">点击夏雨荷才走</button>
<button class="button2">点击夏雨荷才走2</button>
<div></div>
<span>夏雨荷</span>
样式
<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>