监控导航功能:逻辑判断

时间:2019-01-08 08:23:29

标签: javascript performance optimization logic

监视导航功能:逻辑判断

编写一个简单的监视导航功能。

  • 感觉逻辑判断仍然需要优化。
  • 我目前尚不清楚。 (关于代码逻辑)。例如减少if语句
  • 如何优化此代码的性能?
<!-- =panel: start -->
<div class="panel" role="region"></div>
<!-- =panel: end -->

<script>
    var em = document.querySelectorAll(".panel");
    var viewHeight = window.innerHeight;
    var clientHeight = document.body.clientHeight;
    var timeOut = null;

    em.forEach(function (em, index) {
        watchNav(em);
    });

    function watchNav(em) {
        var emHeight = em.offsetHeight;
        var emTop = em.offsetTop;
        clearTimeout(timeOut);

        window.addEventListener("scroll", function (e) {
            var scrollY = window.scrollY;

            timeOut = setTimeout(function () {
                // Logical judgment: how to optimize, want better implementation.
                // Such as reducing the if statement
                // ++++++++++++++++
                if (scrollY > emTop || scrollY + viewHeight / 2 > emTop || scrollY + viewHeight > emTop + emHeight) {
                    console.log("...activing...");
                    em.classList.add("view-focus");
                }
                else {
                    console.log("none");
                    em.classList.remove("view-focus");
                }

                if (scrollY > emTop + emHeight / 2) {
                    console.log("none");
                    em.classList.remove("view-focus");
                }
                // ++++++++++++++++
            }, 40);
        }, false);
    }
</script>

0 个答案:

没有答案
相关问题