欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

animation动画封装函数(js小案例)

程序员文章站 2022-05-04 19:55:06
...

animation动画封装函数(js小案例)
animation动画封装函数(js小案例)

function animation(obj, target, callback) {
    clearInterval(obj.timer); /* 让每次只有一个定时器 */
    obj.timer = setInterval(move, 30);
    // 1. 不占内存   2. 避免命名冲突
    function move() {
        /* 将目标值取整 */
        var step = (target - obj.offsetLeft) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step); /* key */

        obj.style.left = obj.offsetLeft + step + 'px';
        if (target == obj.offsetLeft) {
            clearInterval(obj.timer);
            if (callback) {
                callback();
            }
        }
    }
}
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        div.sliderbar {
            position: absolute;
            right: -100px;
            background-color: aqua;
            width: 120px;
            height: 20px;
        }
        
        div.sliderbar span {
            position: absolute;
            width: 20px;
            z-index: 1;
        }
        
        div.sliderbar div.con {
            position: absolute;
            display: inline-block;
            width: 100px;
            right: 0;
            background-color: aqua;
        }
    </style>
</head>

<body>
    <div class="sliderbar">
        <span></span>
        <div class="con">问题反馈</div>
    </div>
    <script src="animate.js"></script>
    <script>
        var sliderbar = document.querySelector('.sliderbar');
        var con = document.querySelector('.con');
        var span = document.querySelector('span');
        sliderbar.addEventListener('mouseenter', function() {
            animation(con, -80, function() {
                span.innerHTML = "右";
            });
        })
        sliderbar.addEventListener('mouseleave', function() {
            animation(con, 20, function() {
                span.innerHTML = "左";
            });
        })
    </script>
</body>

</html>