缓冲运动
- 缓冲运动: 在固定距离中做减速运动
- 缓冲运动与减速运动的区别: 减速运动不确定最终停止的位置,缓冲运动在特定位置停止。
- 效果:
- 代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box {
position: fixed;
bottom: 300px;
width: 100px;
height: 100px;
border-radius: 50%;
background: rgb(223, 167, 14);
}
</style>
</head>
<body>
<!-- 在减速运动与缓冲运动的区别:减速运动不确定最终停止的位置,缓冲运动在特定位置停止 -->
<div class="box"></div>
<script>
// 在固定距离中做减速运动
//当box的left = 600的时候,就停止
let box = document.querySelector('.box');
let x = 0;
let speed = 120; //初始速度
var target = 600; //目标距离,停止的位置
let timer = setInterval(() => {
//速度逐渐减小,10为一个系数,在目标值与走过的距离相等时,速度变为0
/*
(1)speed = (target - x)/ 10;时,left存在小数
(2)直接取整时:speed = parseInt((target - x)/ 10);
最终x一直为591:
比如为x到了591
speed:600-591=> 9 => 0.9 => 0(取整速度就为0了)
继续走下一步:x = x + speed;因为speed为0,此时x不会在改变了。
x始终无法等于target(600),定时器不会清除
(3)采用向上取整:考虑到最后的speed将减小到0-1之间的小数(比如0.9、 0.8、 0.7),
采用向上取整时,speed都会变成1,x也会一直保持增加,知道x到了600,speed变为0。且满足了x==600==target,会清除定时器。
添加测试(查看变化):console.log("速度为" + speed);
console.log("x="+x);
*/
speed = Math.ceil((target - x) / 10);//向上取整
console.log("速度为" + speed);
// 走过的距离
x = x + speed;
console.log("x="+x);
// 当走过的距离达到目标位置时,就清除定时器
if (x == target) {
clearInterval(timer);
console.log(1)
}
box.style.left = x + 'px';
}, 100)
</script>
</body>
</html>
封装动画函数
将该缓冲运动应用到对某一元素的一些属性的变化上,把该功能封装成一个函数。
测试函数案例:将div的宽高增加到600px与300px
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>封装缓冲函数</title>
<script src="util.js"></script>
<style>
.box {
position: absolute;
left: 0px;
width: 100px;
height: 100px;
background: rgb(21, 147, 185);
}
</style>
</head>
<body>
<div class="box"></div>
<script>
let box = document.querySelector('.box');
move(box, {
width: 600,
height: 300
})
/*
参数:(1)使用动画的元素elem
(2)使用动画的属性以及每个属性的目标值attr_tar_option {}
{
width:600;
height:300;
}
*/
function move(elem, attr_tar_option