如果看物体直线缓冲运动不是太明白,可以先看物体直线运动(地址链接:https://blog.csdn.net/JEFF_luyiduan/article/details/103821605)
物体直线缓冲运动:(从左向右或者从右向左)
物体的速度 距离目标点越近 就越小 当到达目标点时 速度减小为0
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>温故而知新</title>
<style>
div {
width: 100px;
height: 100px;
background-color: #ff0000;
position: absolute;
left: 0px;
top: 0px;
}
span {
position: absolute;
width: 1px;
height: 100px;
background-color: #333333;
top: 0;
left: 300px;
}
button {
margin-top: 200px;
}
</style>
</head>
<body>
<div></div>
<span></span>
<button>点击移动方格</button>
</body>
<script>
/*
物体直线缓冲运动:(从左向右或者从右向左)
物体的速度 距离目标点越近 就越小 当到达目标点时 速度减小为0
*/
let div = document.getElementsByTagName("div")[0];
const button = document.getElementsByTagName("button")[0];
button.onclick = function () {
starMove(div, 7, 300)
}
function starMove(elem, distance, site) {
let moveDiv = null;
clearInterval(moveDiv)
const moveDistance = site - elem.offsetLeft > 0 ? distance : -distance;
moveDiv = setInterval(function () {
if (Math.abs(site - elem.offsetLeft) < Math.abs(moveDistance)) {
elem.style.left = site + "px";
clearInterval(moveDiv)
} else {
elem.style.left = elem.offsetLeft + moveDistance + 'px';
}
}, 70)
}
</script>
</html>
进度条(类似于):
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>温故而知新</title>
<style>
div {
width: 700px;
height: 70px;
background-color: #ff0000;
position: absolute;
left: -630px;
top: 0px;
}
div span {
position: absolute;
width: 70px;
height: 70px;
background-color: #ff00ff;
right: 0;
top: 0;
}
</style>
</head>
<body>
<div class="gaine">
<span></span>
</div>
</body>
<script>
/*
缓冲运动:进度条(类似于)
*/
let gaine = document.getElementsByClassName("gaine")[0];
let timer = null;
gaine.onmouseenter = function () {
startMove(this, 0)
}
gaine.onmouseleave = function () {
startMove(this, -630)
}
function startMove(dom, target) {
clearInterval(timer);
var iSpeed = null;
timer = setInterval(function () {
iSpeed = (target - gaine.offsetLeft) / 7;
// ....
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if (gaine.offsetLeft == target) {
clearInterval(timer);
} else {
gaine.style.left = gaine.offsetLeft + iSpeed + 'px';
}
}, 30);
}
</script>
</html>