js实现锚点跳转
使用 scrollIntoView 方法
通过 document.getElementById 或 document.querySelector 获取目标元素,调用 scrollIntoView 方法实现平滑滚动。支持配置滚动行为(平滑或瞬间)。
document.getElementById('targetElement').scrollIntoView({
behavior: 'smooth'
});
通过修改 window.location.hash
直接修改 window.location.hash 属性为锚点 ID,浏览器会自动跳转。适用于传统锚点跳转,但滚动效果可能不平滑。
window.location.hash = 'section1';
使用 scrollTo 方法
通过 window.scrollTo 指定滚动位置,结合 getBoundingClientRect 获取目标元素的坐标。支持自定义偏移量。
const element = document.getElementById('targetElement');
const offset = 50; // 偏移量
window.scrollTo({
top: element.getBoundingClientRect().top + window.pageYOffset - offset,
behavior: 'smooth'
});
监听锚点点击事件
为所有锚点链接添加事件监听器,阻止默认行为并手动实现滚动。适用于需要统一控制跳转逻辑的场景。
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
兼容性处理
对于不支持 behavior: 'smooth' 的旧浏览器,可使用 polyfill 或 CSS 实现平滑滚动。例如通过 CSS 设置全局滚动行为:
html {
scroll-behavior: smooth;
}
动态锚点跳转
结合路由或动态内容生成锚点,需确保目标元素已渲染后再执行跳转。例如在 setTimeout 或 nextTick 中延迟调用。
setTimeout(() => {
document.getElementById('dynamicSection').scrollIntoView();
}, 300);






