<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
div{
width: 100px;
height: 100px;
background: pink;
position: absolute;
top: 300px;
left: 200px;
}
</style>
</head>
<body>
<button id="btn1">向左</button>
<button id="btn2">向右</button>
<div id="box"></div>
</body>
</html>
<script type="text/javascript">
function $ (id){
return document.getElementById(id)
}
var box = $("box");
var btn1= $("btn1");
var btn2= $("btn2");
btn1.onclick = function(){
animate(box,0)
}
btn2.onclick = function(){
animate(box,200)
}
var timer;
function animate(obj,target){
clearInterval(timer);
timer = setInterval(function(){
var speed = target - obj.offsetLeft > 0 ? 5 : -5;
if(obj.offsetLeft == target){
clearInterval(timer);
}else{
obj.style.left = obj.offsetLeft + speed + 'px';
}
},30)
}
</script>
小盒子左右匀速运动
最新推荐文章于 2024-02-19 14:00:23 发布