<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title>缓冲运动</title>
<style>
*{
padding: 0;
margin: 0;
}
#btn{
position: absolute;
top: 150px;
left: 20px;
padding: 5px;
}
body div:first-of-type{
width: 100px;
height: 100px;
background: red;
position: absolute;
top: 200px;
left: 700px;
}
body div:nth-of-type(2){
width: 1px;
height: 500px;
background: black;
position: absolute;
left: 400px;
}
</style>
<script>
window.onload = function(){
var btn = document.getElementById("btn");
var target = document.getElementsByTagName("div")[0];
var endPos = document.getElementsByTagName("div")[1].offsetLeft;
var timer = null;
btn.onclick = function(){
move()
}
function move(){
clearInterval(timer);
timer = setInterval(function(){
var speed = (endPos - target.offsetLeft)/10;
speed = speed>0 ? 7 : -7;
target.style.left = target.offsetLeft + speed + "px";
document.getElementsByTagName("span")[0].innerHTML = target.offsetLeft+ "," + speed;
}, 30);
}
}
</script>
</head>
<body>
<button id="btn">移动</button><span></span>
<div>
</div>
<div>
</div>
</body>
</html>
yunsu1.gif
改
function move(){
clearInterval(timer);
timer = setInterval(function(){
var speed = (endPos - target.offsetLeft)/10;
speed = speed>0 ? 7 : -7;
if(Math.abs(endPos - target.offsetLeft) <= 7){
clearInterval(timer);
target.style.left = endPos+"px";
}else{
target.style.left = target.offsetLeft + speed + "px";
}
document.getElementsByTagName("span")[0].innerHTML = target.offsetLeft+ "," + speed;
}, 30);
}
yunsu2.gif
网友评论