定时器缓动动画公式:
<!DOCTYPE html>
<html>
<head>
<meat charset="utf-8">
<title>缓动动画</title>
<style>
*{
padding: 0;
margin: 0;
}
body{
background-color: #000;
}
#btn{
width: 80px;
height: 40px;
font-size: 16px;
color: red;
border: 2px solid yellow;
box-shadow: 0 0 10px blue;
margin-top: 30px;
margin-bottom: 30px;
margin-left: 50%;
}
#box{
width: 200px;
height: 200px;
background-color: red;
border: 1px solid #ccc;
box-shadow: 0 0 10px green;
border-radius: 50%;
margin-left: 5px;
}
</style>
</head>
<body>
<button id="btn">开始运动</button>
<div id="box"></div>
<script>
//监听按钮点击事件
$("btn").onclick=function(){
//定义变量
var timer=null;
var begin=0;
var target=800;
//清除定时器
clearInterval(timer);
//开启定时器
timer=setInterval(function(){
//起始值+=(目标值-起始值)*缓动系数;
begin+=(target-begin)*0.5;
// console.log(Math.round(begin));
//判断
if(Math.round(begin)>=target){
begin = target;
clearInterval(timer);
}
//运动
$("box").style.marginLeft = begin+‘px‘;
},100);
}
function $(id){
return typeof id==="string"?document.getElementById(id):null;
}
</script>
</body>
</html>
原文:https://www.cnblogs.com/zhang-jiao/p/9693695.html