js 实现锚
使用 scrollIntoView 方法
通过 Element.scrollIntoView() 方法实现平滑滚动到目标元素。此方法支持配置滚动行为(如平滑或瞬间滚动)。

document.getElementById('targetElement').scrollIntoView({
behavior: 'smooth'
});
动态生成锚点链接
结合 querySelector 和事件监听,动态处理页面内的锚点跳转,避免 URL 哈希变化。

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function(e) {
e.preventDefault();
const target = document.querySelector(this.getAttribute('href'));
if (target) target.scrollIntoView({ behavior: 'smooth' });
});
});
自定义滚动动画
使用 window.scrollTo 配合 requestAnimationFrame 实现更灵活的滚动效果,例如控制滚动速度或添加中间动画。
function scrollToElement(element, duration = 500) {
const start = window.pageYOffset;
const target = element.getBoundingClientRect().top + start;
const startTime = performance.now();
function animateScroll(currentTime) {
const elapsed = currentTime - startTime;
const progress = Math.min(elapsed / duration, 1);
window.scrollTo(0, start + (target - start) * progress);
if (progress < 1) requestAnimationFrame(animateScroll);
}
requestAnimationFrame(animateScroll);
}
// 调用示例
scrollToElement(document.getElementById('section2'));
兼容性处理
对于旧版本浏览器,可通过检测 scrollBehavior 支持性提供回退方案。
if (!('scrollBehavior' in document.documentElement.style)) {
// 使用 polyfill 或自定义动画
}
注意事项
- 确保目标元素存在且可见,避免滚动失效。
- 平滑滚动可能受浏览器或系统设置影响,需测试不同环境。
- 动态加载内容需在元素渲染完成后调用滚动方法。






