当使用纯CSS实现点击链接跳转到页面中的某个元素(通过ID)时,有时会遇到页面滚动停在滑块顶部的情况。这通常是由于浏览器的默认行为与CSS的滚动行为之间的冲突导致的。
<a href="#id">
的形式,点击链接可以直接跳转到页面中具有相应ID的元素位置。scroll-behavior: smooth;
属性,可以实现平滑滚动效果。假设页面中有以下结构:
<div id="section1">Section 1</div>
<a href="#section1">Go to Section 1</a>
纯CSS方法:
html {
scroll-behavior: smooth;
}
JavaScript辅助方法:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
通过上述方法,可以有效解决点击链接时页面滚动停在滑块顶部的问题,提升用户体验。
领取专属 10元无门槛券
手把手带您无忧上云