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

点击及滚动页面时切换导航active类并修改活跃导航项内容的实现问题

导航栏激活功能实现方案

现有代码问题

你当前的代码混淆了原生JavaScript与jQuery的语法,同时存在以下错误:

  • document.querySelector仅能匹配首个符合条件的元素,要选中所有导航项需使用document.querySelectorAll
  • removeClass、hasClass是jQuery专属方法,原生JS需使用classList API操作类名
  • 缺少滚动监听逻辑,无法实现滚动到对应区块自动激活导航的功能
  • 没有存储导航原始文本,切换激活状态后无法恢复原内容

1. 补充CSS样式

你原有CSS中未定义激活状态的样式,可添加如下代码自定义激活效果:

.nav-link.active {
  color: #43b0f1 !important;
  font-weight: 700;
}

2. 替换JavaScript代码

以下是原生JS实现的完整代码,可直接替换你现有错误代码:

// 预存导航项原始文本,避免切换后丢失
const navLinks = document.querySelectorAll('.nav-link');
const navOriginalTexts = Array.from(navLinks).map(link => link.textContent);
// 匹配页面对应id的内容区块,如果你用的是div标签做区块,把选择器改为div[id]即可
const contentSections = document.querySelectorAll('section[id]');

// 通用激活导航方法
function setActiveNav(targetHash) {
  // 重置所有导航项状态
  navLinks.forEach((link, idx) => {
    link.classList.remove('active');
    link.textContent = navOriginalTexts[idx];
  });
  // 激活目标导航项并修改文本
  const targetNav = document.querySelector(`.nav-link[href="${targetHash}"]`);
  if (targetNav) {
    targetNav.classList.add('active');
    targetNav.textContent = `<${targetNav.textContent}/>`;
  }
}

// 点击导航项触发激活
navLinks.forEach(link => {
  link.addEventListener('click', function(e) {
    const targetHash = this.getAttribute('href');
    setActiveNav(targetHash);
    // 以下为平滑滚动逻辑,不需要可删除
    const targetSection = document.querySelector(targetHash);
    if (targetSection) {
      e.preventDefault();
      targetSection.scrollIntoView({ behavior: 'smooth' });
    }
  });
});

// 滚动页面自动匹配激活导航
window.addEventListener('scroll', () => {
  let currentHash = '';
  contentSections.forEach(section => {
    const sectionTop = section.offsetTop;
    const sectionHeight = section.offsetHeight;
    // 偏移量可根据你的导航栏高度自行调整
    if (window.scrollY >= sectionTop - 120) {
      currentHash = `#${section.id}`;
    }
  });
  if (currentHash) setActiveNav(currentHash);
});

// 页面加载完成后默认激活第一个导航项,不需要可删除
window.addEventListener('load', () => setActiveNav('#home'));

注意事项

  • 确保页面内存在id为home、about、skills、contact的内容区块,滚动激活功能才能正常生效
  • 如果需要在激活状态插入HTML标签而非纯文本,将代码中的textContent替换为innerHTML即可

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:24:04