<!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>
ul {
position: relative;
margin: 100px auto 0px;
width: 800px;
height: 100px;
}
ul .ele {
float: left;
width: 198px;
border: 1px solid black;
background: orange;
height: 98;
line-height: 98px;
text-align: center;
list-style: none;
}
.bg {
position: absolute;
left: 0px;
top: 0px;
width: 200px;
height: 100px;
opacity: 0.4;
background: deeppink;
list-style: none;
}
</style>
</head>
<body>
<ul>
<li class="ele">cst</li>
<li class="ele">cg</li>
<li class="ele">dg</li>
<li class="ele">dcg</li>
<li class="bg"></li>
</ul>
</body>
<script>
const li = document.getElementsByTagName("li");
const lastLi = li[li.length - 1];
let timer = null;
for (let i = 0; i < li.length - 1; i++) {
li[i].onmouseenter = function () {
startMove(lastLi, this.offsetLeft)
}
}
function startMove(dom, target) {
clearInterval(timer);
let a = 2;
let iSpeed = 7;
let u = 0.7;
timer = setInterval(() => {
a = (target - dom.offsetLeft) / 7
iSpeed = (iSpeed + a) * u;
if (Math.abs(iSpeed) < 1 && Math.abs(target - dom.offsetLeft) < 1) {
dom.style.left = target;
clearInterval(timer)
} else {
dom.style.left = dom.offsetLeft + iSpeed + "px";
}
}, 20);
}
</script>
</html>