加减速运动是加速运动和减速运动的结合。前半段运动时,做加速运动。到达指定点时,做减速运动,最终到达终点停止
step = 0.02(v0+a*(0.02n+0.01)) = 2/10000(100*v0+a(2n+1))
假设v0=0,最终速度v=100,距离s = 200
所以a = v*v/(2*s) = 5000/s = 25
则加速运动的step = (2n+1)/s =(2n+1)/200
在加速运动中,s=1/2*a*t*t;
所以加速运动总时间t = s/50 = 4,定时器运行次数n = t/0.02=200次
减速运动的step=0.02(v0-(2n+1)),此时的v0相应于加速运动结束时的瞬时速度100,a= -5000/s = -25
所以,减速运动的step=2-(2n+1)/s = 2-(2n+1)/200
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="btn">开始运动</button>
<button id="reset">还原</button>
<div id="test" style="height: 100px;width: 100px;background-color: pink;position:absolute;left:0;"></div>
<div style="background-color:blue;width:1px;height:100px;position:absolute;left:200px;"></div>
<div style="background-color:red;width:1px;height:100px;position:absolute;left:400px;"></div>
<script>
function getCSS(obj,style){
if(window.getComputedStyle){
return getComputedStyle(obj)[style];
}
return obj.currentStyle[style];
}
reset.onclick = function(){history.go();}
btn.onclick = function(){
//声明定时器运行次数
var index=-1;
//声明步长值step
var step;
//声明当前值cur
var cur;
//声明目标值
var target = parseFloat('400px');
clearInterval(test.timer);
test.timer = setInterval(function(){
//更新定时器的工作次数
index++;
//当index为200时,说明进行完一次运动,则将index置0
if(index == 200){
index = 0;
};
//更新当前值
cur = parseFloat(getCSS(test,'left'));
//更新步长值
//加速运动
if(cur < 200){
step =(2*index+1)/(target/2);
}else{
//减速运动
step = 2-(2*index+1)/(target/2);
}
//若步长设置值使得元素超过目标点时,将步长设置值更改为目标点值 - 当前值
if((cur+step-target)*step>0){
step = target - cur;
}
//更新left值
test.style.left = cur + step + 'px';
//当元素到达目标点时,停止定时器
if(step == target - cur){
clearInterval(test.timer);
}
},20);
}
</script>
</body>
</html>
原文链接:https://www.qiquanji.com/post/8050.html
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
微信扫码关注
更新实时通知
