<!DOCTYPE html>
<html>
<head lang="en">
<meta charset="UTF-8">
<title></title>
<style>
*{
margin: 0;
padding: 0;
}
#box{
width: 100px;
height: 100px;
background-color: pink;
position: absolute;
left: 0;
top: 50px;
}
</style>
</head>
<body>
<button id="btn200">200</button>
<button id="btn400">400</button>
<div id="box"></div>
</body>
</html>
<script>
var btn200 = document.getElementById("btn200");
var btn400 = document.getElementById("btn400");
var box = document.getElementById("box");
btn200.onclick = function () {
animate(box,200);
}
btn400.onclick = function () {
animate(box,400);
}
function animate(obj,target){
//盒子本身位置+步长
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var step = (target-obj.offsetLeft)/10; //步长
step = step>0?Math.ceil(step):Math.floor(step);//步长取整
obj.style.left = obj.offsetLeft + step + "px";
if(target == obj.offsetLeft){
clearInterval(obj.timer);
}
},30);
}
</script>
封装缓动动画函数
最新推荐文章于 2021-11-29 13:01:00 发布