从零到一学JS:用原生JS写个导航栏

146 阅读1分钟

每日一kun:不要以为自己坚持不来,你一定会坚持熬夜玩手机。

尝试用原生JS写导航栏,原理就是通过mouseenter加mounseleave事件加上回调函数完成导航栏伸出伸进,不用原生JS写下,永远感受不到框架的魅力,不过能用JS独立完成肯定以后对阅读框架源码更有帮助。

JS代码
  var span = document.querySelector("span")
    var div = document.querySelectorAll("div")

    var packageTimer = function (obj, away, comeBack) {
        var target = obj.offsetLeft + away
        clearInterval(obj.timer)
        obj.timer = setInterval(function () {
            var step = (away - obj.offsetLeft) / 100
            if (away < 0) {
                step = step > 0 ? Math.ceil(step) : Math.floor(step)
                if (obj.offsetLeft <= target) {
                    clearInterval(obj.timer)
                    if (comeBack) {
                        comeBack()
                    }
                }
            } else {
                step = -step
                step = step > 0 ? Math.ceil(step) : Math.floor(step)
                if (obj.offsetLeft >= target) {
                    clearInterval(obj.timer)
                    if (comeBack) {
                        comeBack()
                    }
                }
            }

            obj.style.left = obj.offsetLeft + step + "px"

        }, 20)
    }


    span.addEventListener("mouseenter", function () {

        packageTimer(div[1], -150, function () {
            span.innerHTML = "👉"

        })
    })
    span.addEventListener("mouseleave", function () {

        packageTimer(div[1], 150, function () {
            span.innerHTML = "👈"

        })
    })
HTML代码
    <div class="main">
        <span>👈</span>
        <div class="con">内容显示</div>
    </div>
CSS代码
    .main {
        display: flex;

        height: 300px;

        margin-top: 200px;
        justify-content: flex-end;

    }

    span {
        background-color: yellowgreen;
        width: 50px;
        height: 40px;
        position: absolute;
        text-align: center;
        z-index: 10;
        line-height: 40px;

    }

    .con {
        background-color: yellowgreen;
        width: 200px;
        height: 40px;
        text-align: center;
        align-items: center;
        position: absolute;
        line-height: 40px;
        right: -150px;

    }

    body {
        overflow: hidden;
    }

结果

2022-12-13-01-51-58.gif

Tips:100多行代码使用emlemnt 应该不超过10行搞定,怪不得框架提高生产力,不过使用框架虽然提升了效率,但也同样就无法定制化开发,就比如我这个动画现在是变速出现,我可以用JS改成匀速出现,也可以改变其他东西,而框架就能按照它的源码使用,不过也可以改源码实现,如果能看懂。