<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
body {
margin: 0;
}
#box {
width: 100px;
height: 100px;
background-color: pink;
position: relative; /*右移位置改变脱离文档流*/
}
#box1 {
width: 100px;
height: 100px;
margin-top: 10px;
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. 点击按钮让盒子向右移动 盒子从800 到400的速度很慢原因分析 解决:给body清空margin
btn1.onclick = function () {
animation(box, 400);
animation(box1, 400);
// console.log(box.style.left); // 第一次:空字符串 第二次:18px
// console.log(box.offsetLeft); // 第一次:8 body自带的margin值 第二次:26=8+18
// box.style.left = box.offsetLeft + 10 + 'px';
// console.log(box.style.left); // 第一次:18 box设置的是相对定位,不包含body自带的margin值8px,而是相当于第一次的初始位置右移了8+10=8px 第二次:36px
// console.log(box.offsetLeft); // 第一次:26 第二次:44=26+10+8 每次都加了一个body自带的margin值
}
btn2.onclick = function () {
animation(box, 800);
animation(box1, 800);
// console.log(box.offsetLeft); // 第一次:44 第二次:42 每次只移动了很小的距离
// console.log(box.style.left); // 第一次:36px 第二次:34px
// box.style.left = box.offsetLeft - 10 + 'px';
// console.log(box.offsetLeft); // 第一次:42 第二次:40
// console.log(box.style.left); // 第一次:34px 第二次:32px
}
// 动画封装
// var timerId = null; // 需全局变量
function animation(element, target) {
// 给每个element增加一个属性timerId,保证定时器标志互不干扰
if (element.timerId) {
clearInterval(element.timerId);
timerId = null;
}
element.timerId = setInterval(function () {
// 步距
var step = 6;
var current = element.offsetLeft;
// 盒子从400 到800 执行动画
// 盒子从800 到400 不执行动画
// 如果当前位置 > 目标位置 step < 0
if (current > target) {
step = -Math.abs(step);
}
// 当前位置和目标位置的差值小于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>