<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.box {
position: absolute;
left: 700px;
top: 0;
width: 100px;
height: 100px;
background-color: #ccc;
}
span {
position: absolute;
width: 1px;
height: 500px;
left: 300px;
top: 0px;
background-color: red;
}
button {
margin-top: 200px;
}
</style>
</head>
<body>
<div class="box">
</div>
<span></span>
<button id="move">move</button>
<script>
window.onload = function() {
var oBox = document.querySelector(".box");
var oButton = document.querySelector("#move");
var speed = 13;
var target = 300;
oButton.addEventListener("click", function() {
// 根据左右位置计算速度
var speed = target > oBox.offsetLeft ? 7 : -7;
oBox.timer = setInterval(function() {
// offsetLeft 的值是只读属性,不能被修改,
// 所以说left 始终等于 0px ,所以动画失效!
// oBox.offsetLeft += speed;
// oBox.style.left = oBox.offsetLeft + "px";
//修改如下操作
var left = oBox.offsetLeft + speed;
// 边界处理问题!
// if (speed > 0) {
// // 解决边界处理问题!
// if (left >= target) {
// clearInterval(oBox.timer)
// oBox.timer = null;
// oBox.style.left = target + "px";
// } else {
// oBox.style.left = left + "px";
// }
// } else {
// if (left <= target) {
// clearInterval(oBox.timer)
// oBox.timer = null;
// oBox.style.left = target + "px";
// } else {
// oBox.style.left = left + "px";
// }
// }
// 对上面代码进行优化处理
if (Math.abs(left - target) < Math.abs(speed)) {
clearInterval(oBox.timer)
oBox.timer = null;
oBox.style.left = target + "px";
} else {
oBox.style.left = left + "px";
}
}, 50)
})
}
</script>
</body>
</html>
重点, 1 offsetLeft 值不能设置,只能读取
2, 匀速运动,有两个方向,要进行分别处理
3, 当我们分别处理后,发现,代码没有多大区别,这个时候,要进行代码合并操作