js 弹性运动案例

<!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>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值