
在使用弹性运动时,需要注意一些小问题,即运动的元素所要改变的属性值不能太小,如果太小在反弹时就会出现负值,导致出现错误,所以要给出一定的限制,下面写一个小Demo,欢迎大家复制粘贴及吐槽。
先来看一下效果图:

以下是代码实现:
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>原生JS实现弹性运动中需要注意的问题</title>
<style>
#box {
width: 100px;
height: 30px;
background: red;
}
</style>
</head>
<body>
<div id="box"></div>
<script>
window.onload = function () {
var myBox = document.getElementById('box');
myBox.onmouseover = function () {
startMove(myBox, 200);
};
myBox.onmouseout = function () {
startMove(myBox, 40);
};
};
var speed = 0;
var height = 40;
function startMove(obj, target) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
speed += (target - height) / 5;
speed *= 0.7;
if (Math.abs(speed) < 1 && Math.abs(target - height) < 1) {
clearInterval(obj.timer);
obj.style.height = target + 'px';
} else {
height += speed;
// 弹性运动过程中,反弹时可能导致高度为0,出现报错,所以要限制
if (height < 0) {
height = 0;
}
// 当高度太小,即便限制,实际效果也会有些卡顿
obj.style.height = height + 'px';
}
}, 30);
}
</script>
</body>
</html>