You need to enable JavaScript to run this app. JS实现动态导航栏点击链接跳转至页面底部而非对应分区问题排查
优惠活动
大模型
产品
解决方案
定价
更多

JS实现动态导航栏点击链接跳转至页面底部而非对应分区问题排查

问题原因
  • 核心原因是for...of循环中的section变量未声明块级作用域:你使用的for(section of sections)写法没有添加let关键字,导致section被挂载为全局变量,每轮循环都会覆盖上一轮的section取值。
  • 循环结束后section最终指向页面最后一个<section>节点,所有导航链接的点击事件触发时,调用的section.scrollIntoView()本质都是滚动到最后一个章节,就会出现总是跳转页面底部的表现。
  • 额外存在不规范问题:a标签的href属性直接填写section的id值,缺少#锚点前缀,只是因为你加了e.preventDefault()阻止了默认跳转行为才没触发错误。
修复方案

只需要调整2处代码即可:

  1. 给循环变量添加let声明,让每轮循环的section为独立块级变量,正确绑定对应章节节点
  2. 修正href属性的锚点写法,保证代码规范性

修复后的完整JS代码如下:

const Ul = document.querySelector('ul');
const sections = document.querySelectorAll('section');
// 给循环变量加let声明
for(let section of sections) {
    //create li:
    const li_items = document.createElement("li");
    
    //create new anchor elements:
    const li_links = document.createElement("a");
    
    //give anchor elements a hyperlinks: 补全#前缀
    const IdAttribute = section.getAttribute('id');
    li_links.setAttribute('href', `#${IdAttribute}`);

    //get the names of the sections:
    const navData = section.getAttribute("data-nav");
    const text = document.createTextNode(navData);
    
    //give the navbar style :
    li_links.classList.add("menu__link");

    Ul.appendChild(li_items);
    li_items.appendChild(li_links);
    li_links.appendChild(text);

    //scroll to section when click on nav links 可加smooth参数实现平滑滚动
    li_links.addEventListener('click', e => {
        e.preventDefault();
        section.scrollIntoView({behavior: 'smooth'})
    });
}
//end of the navbar.

如果需要兼容旧浏览器,也可以改用事件委托的方式实现,避免循环绑定事件的作用域问题:

const Ul = document.querySelector('ul');
const sections = document.querySelectorAll('section');

// 先批量渲染导航
for(let section of sections) {
    const li_items = document.createElement("li");
    const li_links = document.createElement("a");
    const IdAttribute = section.getAttribute('id');
    li_links.setAttribute('href', `#${IdAttribute}`);
    const navData = section.getAttribute("data-nav");
    const text = document.createTextNode(navData);
    li_links.classList.add("menu__link");
    Ul.appendChild(li_items);
    li_items.appendChild(li_links);
    li_links.appendChild(text);
}

// 统一给导航容器绑定点击事件
Ul.addEventListener('click', e => {
    if(e.target.classList.contains('menu__link')) {
        e.preventDefault();
        const targetId = e.target.getAttribute('href').slice(1);
        const targetSection = document.getElementById(targetId);
        targetSection.scrollIntoView({behavior: 'smooth'});
    }
})

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.11 23:21:00