滚动与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
相关产品推荐
相关产品推荐

