<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
#box {
width: 100px;
height: 100px;
background-color: pink;
position: relative; /*右移位置改变脱离文档流*/
}
#box1 {
width: 100px;
height: 100px;
background-color: blue;
position: relative; /*右移位置改变脱离文档流*/
}
</style>
</head>
<body>
<input type="button" value="动画400" id="btn1">
<input type="button" value="动画800" id="btn2">
<div id="box"></div>
<div id="box1"></div>
<script>
var btn1 = document.getElementById('btn1');
var btn2 = document.getElementById('btn2');
var box = document.getElementById('box');
var box1 = document.getElementById('box1');
// 1. 点击按钮让盒子向右移动
btn1.onclick = function () {
animation(box, 400);
animation(box1, 400);
}
btn2.onclick = function () {
animation(box, 800);
animation(box1, 800);
}
// 动画封装
// var timerId = null; // 需全局变量
function animation(element, target) {
// 给每个element增加一个属性timerId,保证定时器标志互不干扰
if (element.timerId) {
clearInterval(element.timerId);
timerId = null;
}
element.timerId = setInterval(function () {
// 步距
var step = 10; // 6、5的时候先点击400 再点800 再点400会一直往右走 设置body的margin为0后正常
var current = element.offsetLeft;
// 盒子从400 到800 执行动画
// 盒子从800 到400 不执行动画
// 如果当前位置 > 目标位置 step < 0
if (current > target) {
step = -Math.abs(step);
}
// 当前位置和目标位置的差值小于step
// console.log(Math.abs(current - target));
// console.log(Math.abs(step));
if (Math.abs(current - target) < Math.abs(step)) {
// 停止定时器
clearInterval(element.timerId);
element.style.left = target + 'px'; // 赋值为目标值
// 退出函数
return;
};
current += step;
element.style.left = current + 'px';
}, 30);
}
</script>
</body>
</html>