You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

滚动与hover触发header类切换的条件逻辑异常问题

导航hover与滚动类切换冲突问题修复

问题根源

你的代码中checkIsTop()仅在页面初始化时执行一次,给导航链接绑定mouseenter/mouseleave事件后,即便滚动超过120px让data-is-top变为false,这些事件监听器不会自动移除,所以hover仍会触发color-swap类的添加,导致逻辑失效。

解决方案

不需要反复绑定/移除事件,直接在hover事件触发时实时判断data-is-top的状态,只有当状态为true时才执行类的切换操作;同时保留滚动逻辑,并且排除News和Contact页面的干扰。

修改后的JS代码

(function ($) {
    $(document).ready(function () {
        const header = document.getElementById('header');
        const links = document.querySelectorAll("#primary-menu > .menu-item-has-children");
        // 排除指定页面
        const isExcludedPage = window.location.pathname.startsWith('/about/contact') || window.location.pathname.startsWith('/news');

        if (!isExcludedPage) {
            // 滚动事件逻辑
            window.addEventListener("scroll", () => {
                const st = $(this).scrollTop();
                if (st > 120) {
                    header.classList.add('color-swap');
                    header.setAttribute('data-is-top', 'false');
                } else {
                    header.classList.remove('color-swap');
                    header.setAttribute('data-is-top', 'true');
                }
            });

            // hover事件逻辑:实时判断data-is-top状态
            links.forEach(link => {
                link.addEventListener("mouseenter", () => {
                    if (header.dataset.isTop === 'true') {
                        header.classList.add('color-swap');
                    }
                });
                link.addEventListener("mouseleave", () => {
                    if (header.dataset.isTop === 'true') {
                        header.classList.remove('color-swap');
                    }
                });
            });
        }
    });
})(jQuery);

关键改动说明

  • 提前判断是否为排除页面,避免不必要的事件绑定
  • 将hover事件的判断逻辑移到事件触发时,每次hover都会检查data-is-top的当前状态,只有在顶部状态下才执行类切换
  • 简化代码结构,去掉冗余的嵌套函数,提升可读性

内容的提问来源于stack exchange,提问作者RRhodes

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:30:44