JS弹性运动
弹性运动:顾名思义,就如同物理中的加速减速运动,当开始时速度过大,到达终点时,速度不会立刻停下,而是再前进一段距离,而后再向相反方向运动,如此往复。
弹性运动会出现有如下几个问题:
1、无法到达指定位置-----小数误差问题
2、如何解决?速度无法取整,使用变态方法----将要改变的值设置成变量
Bash
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<button id="btn1">开始运动</button>
<button id="btn2">暂停</button>
<button id="reset">还原</button>
<div id="test" style="height: 100px;width: 100px;background-color: pink;position:absolute;left:0;top: 30px;border-radius:50%"></div>
<script>
function getCSS(obj,style){
if(window.getComputedStyle){
return getComputedStyle(obj)[style];
}
return obj.currentStyle[style];
}
reset.onclick = function(){history.go();}
btn2.onclick = function(){
clearInterval(test.timer);
}
//声明步长值stepY、stepX
var stepY = 30;
var stepX = 10;
btn1.onclick = function(){
//声明当前值curY、curX
var curY,curX;
//声明目标值
var targetY = parseFloat('400px');
clearInterval(test.timer);
test.timer = setInterval(function(){
//更新当前值
curY = parseFloat(getCSS(test,'top'));
curX = parseFloat(getCSS(test,'left'));
//更新步长值
stepY -= 1;
//当元素返回到初始高度时
if(stepY == -30){
stepY = 29;
stepX = -stepX;
}
//更新top、left值
test.style.top = curY + stepY + 'px';
test.style.left = curX + stepX + 'px';
},20);
}
</script>
</body>
</html>
原文链接:https://www.qiquanji.com/post/8003.html
本站声明:网站内容来源于网络,如有侵权,请联系我们,我们将及时处理。
版权声明
本文仅代表作者观点,不代表本站立场。
本文系作者授权发表,未经许可,不得转载。