<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>弹性案例</title>
<style>
ul{
position: relative;
width: 400px;
display: flex;
padding: 0;
margin: 0 auto;
}
li{
list-style: none;
width: 100px;
height: 60px;
border: 1px solid #1aaba8;
background-color: rgba(0, 0, 0, .2);
text-align: center;
line-height:60px;
cursor: pointer;
}
.bg{
position: absolute;
top: 0;
left: 0;
background-color: aquamarine;
z-index: -1;
}
</style>
</head>
<body>
<ul>
<li>fgfgh11</li>
<li>fgfgh12</li>
<li>fgfgh13</li>
<li>fgfgh14</li>
<li class="bg"></li>
</ul>
<script>
let lis = document.getElementsByTagName('li')
let bg = lis[lis.length-1]
Object.values(lis).forEach((li, i)=>{
if(i < lis.length-1){
li.onmouseenter = function(){
startMove(bg, this.offsetLeft)
}
}
})
let timer = null
function startMove(dom, target){
clearInterval(timer)
let a = 3 // 加速度
let speed = 0 // 速度
let u = .8//.92 // 运动损耗
timer = setInterval(() => {
let difference = target - dom.offsetLeft
// 加速度变化
a = difference/10
speed += a
speed *= u
// 停止条件 在目标位置附近 且速度近视为0
if(Math.abs(speed) <= 1 && Math.abs(difference) <= 1){
clearInterval(timer)
dom.style.left = target + 'px'
return
}
dom.style.left = dom.offsetLeft + speed + 'px'
}, 30);
}
</script>
</body>
</html>
js 弹性运动案例
最新推荐文章于 2021-12-30 11:00:44 发布