<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#dv {
width: 200px;
height: 100px;
background-color: khaki;
margin-top: 20px;
position: absolute;
top: 20px;
left: 0;
}
</style>
</head>
<body>
<input type="button" value="移动到400px" id="btn1"/>
<input type="button" value="移动到800px" id="btn2"/>
<div id="dv">
</div>
<script src="../common.js"></script>
<script>
function changeMove(element,target){
//首先清理定时器
clearInterval(element.timeid);
element.timeid=setInterval(function(){
//获取当前位置
var current=element.offsetLeft;
//设置移动步数
var step=(target-current)/10;
//如果步数是正数向上取整,如果是负数,向下取整
step=step>0?Math.ceil(step):Math.floor(step);
//移动公式
current+=step;
element.style.left =current+"px";
//如果到目的地清理定时器
if(current==target){
clearInterval(element.timeid);
}
//添加测试代码
console.log(current+"px=============="+target+"px============="+step+"px");
},50);
}
my$("btn1").onclick=function(){
changeMove(my$("dv"),400);
};
my$("btn2").onclick=function(){
changeMove(my$("dv"),800);
};
</script>
</body>
</html>
![](https://img.haomeiwen.com/i13694129/9f73b781b8c9b9f5.png)
变速动画.png
网友评论