本文主要介绍如何利用JS以及定位实现元素的减速运动。
1.案例目标
盒子向右进行减速移动,移至300px处即停止
2.核心思路
通过目标位置的值减去盒子距离屏幕左侧的距离,即可得到盒子每次移动前距离目标位置的值。每次盒子移动的距离都是所剩距离的十分之一,循环往复,直至到达目标位置。由于JS小数的计算存在精度问题,故需要进行取整操作。
代码如下:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title></title>
<style type="text/css">
* {
padding: 0px;
margin: 0px;
}
.box {
width: 200px;
height: 200px;
background: blue;
position: absolute;
left: 0px;
transition: left 0.5s;
}
</style>
</head>
<body>
<div class="box"></div>
<script type="text/javascript">
var box = document.querySelector('.box');
linearMove(box, 300);
function linearMove(obj, target) {
var myInter = setInterval(function() {
var offsetLeft = obj.offsetLeft;
var num = (target - offsetLeft) / 10;
num > 0 ? num = Math.ceil(num) : Math.floor(num);
if (offsetLeft == target) {
clearInterval(myInter);
} else {
obj.style.left = offsetLeft + num + 'px';
}
}, 1000)
}
</script>
</body>
</html>
效果如图: