<!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>
* {
margin: 0;
padding: 0;
}
.box {
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 100px;
}
</style>
</head>
<body>
<button id="btn">move-></button>
<button id="btnone"> <-move</button>
<div class="box"></div>
<script>
var btn = document.getElementById('btn');
var btnone = document.getElementById('btnone');
var odiv = document.getElementsByTagName('div')[0];
var timer = null;//初始化一个定时器
var num = 0;
//在之前的基础上继续封装只传一个参数
btn.onclick = function(){
move(500);
}
btnone.onclick = function(){
move(0)
}
// function move(length){
// clearInterval(timer);
// var speed = length-odiv.offsetLeft>0?5:-5;
// timer = setInterval(function(){
// num+=speed;
// if(odiv.offsetLeft === length){
// clearInterval(timer);
// }else{
// odiv.style.left = num+'px';
// }
// },20)
// }
//较之于1和2更加简洁,以上是让速度为5或者-5,能够正好到达target,当不能正好累加到target时另作处理,如下
function move(target){
clearInterval(timer);
timer = setInterval(function(){
var speed = target-odiv.offsetLeft>0?7:-7;
num+=speed;
if(Math.abs(target-odiv.offsetLeft)<7){
odiv.style.left = target+'px';
//当以7px/20ms速度移动时不能正好到达target,此时需要强制拉到终点
clearInterval(timer);
}else{
odiv.style.left = num+'px';
}
},20)
}
</script>
</body>
</html>
如图
image.png
网友评论