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>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章