<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
margin: 0;
}
#box {
position: relative;
width: 100px;
height: 100px;
background-color: red;
}
#box1 {
margin-top: 10px;
position: relative;
width: 100px;
height: 100px;
background-color: blue;
}
</style>
</head>
<body>
<input type="button" id="btn" value="动画 800">
<input type="button" id="btn1" value="动画 400">
<div id="box">
</div>
<div id="box1">
</div>
<script>
var btn = document.getElementById('btn');
var btn1 = document.getElementById('btn1');
var box = document.getElementById('box');
var box1 = document.getElementById('box1');
btn.onclick = function () {
animate(box, 800);
animate(box1, 800);
// console.log(box.style.left);
// console.log(box.offsetLeft);
// box.style.left = box.offsetLeft + 10 + 'px';
// console.log(box.style.left);
// console.log(box.offsetLeft);
}
btn1.onclick = function () {
animate(box, 400);
animate(box1, 400);
// console.log(box.style.left);
// console.log(box.offsetLeft);
// box.style.left = box.offsetLeft - 10 + 'px';
// console.log(box.style.left);
// console.log(box.offsetLeft);
}
// var timerId = null;
// 封装动画的函数
function animate(element, target) {
// 通过判断,保证页面上只有一个定时器在执行动画
if (element.timerId) {
clearInterval(element.timerId);
timerId = null;
}
element.timerId = setInterval(function () {
// 步进 每次移动的距离
var step = 10;
// 盒子当前的位置
var current = element.offsetLeft;
// 当从400 到 800 执行动画
// 当从800 到 400 不执行动画
// 判断如果当前位置 > 目标位置 此时的step 要小于0
if (current > target) {
step = - Math.abs(step);
}
// Math.abs(current - target) < Math.abs(step)
if (Math.abs(current - target) < Math.abs(step)) {
// 让定时器停止
clearInterval(element.timerId);
// 让盒子到target的位置
element.style.left = target + 'px';
return;
}
// 移动盒子
current += step;
element.style.left = current + 'px';
}, 30);
}
</script>
</body>
</html>