JS实现导航点击滚动到指定位置时重复点击异常回顶问题
故障原因
- 导航项默认行为未拦截:如果你的导航项是
<a>标签且href属性为#/空值,点击时会触发浏览器默认的回到顶部行为,你写的window.scrollTo执行后会立刻被默认行为覆盖,只有第一次点击时因为页面还在初始位置、默认跳转和你写的滚动目标刚好重合才会看起来正常。 - 选择器可能匹配错误:如果导航项和对应内容区块用了同名class,
document.querySelector只会返回DOM树中第一个匹配的元素,会出现事件绑定到内容区块而非导航项的问题,触发逻辑完全混乱。 - 硬编码滚动坐标兼容性差:固定写死590、1250这类滚动值,在窗口缩放、内容动态加载、不同分辨率设备上都会出现位置偏移,无法精准定位到目标区块。
修复步骤
- 给导航项单独设置专属class(比如导航的projects按钮加
nav-project类,和内容区的.project类做区分),避免选择器取错元素。 - 点击事件中调用
e.preventDefault()拦截浏览器默认跳转行为。 - 不再硬编码滚动坐标,直接读取目标区块的实时
offsetTop值计算滚动位置,适配所有布局场景。
可直接运行的修复代码
// 绑定导航点击事件,注意替换成你实际的导航项、内容区块选择器 const homeNav = document.querySelector('.nav-home'); const projectNav = document.querySelector('.nav-project'); const skillNav = document.querySelector('.nav-skill'); const aboutNav = document.querySelector('.nav-about'); const hireNav = document.querySelector('.nav-hire'); // 内容区块 const projectSection = document.querySelector('.project'); const skillSection = document.querySelector('.skill'); const aboutSection = document.querySelector('.about'); const hireSection = document.querySelector('.hire'); homeNav.addEventListener('click', (e) => { e.preventDefault(); window.scrollTo({ top: 0, behavior: 'smooth' }); }); projectNav.addEventListener('click', (e) => { e.preventDefault(); window.scrollTo({ top: projectSection.offsetTop, behavior: 'smooth' }); }); skillNav.addEventListener('click', (e) => { e.preventDefault(); window.scrollTo({ top: skillSection.offsetTop, behavior: 'smooth' }); }); aboutNav.addEventListener('click', (e) => { e.preventDefault(); window.scrollTo({ top: aboutSection.offsetTop, behavior: 'smooth' }); }); hireNav.addEventListener('click', (e) => { e.preventDefault(); window.scrollTo({ top: hireSection.offsetTop, behavior: 'smooth' }); });
如果你有固定在顶部的导航栏,计算
top值时减去导航栏的高度即可,避免区块顶部被导航遮挡。
内容的提问来源于stack exchange,提问作者Surge
相关产品推荐
相关产品推荐

