点击锚点时如何判断滚动方向以设置不同偏移量
解决方案
要解决这个问题,核心是在点击锚点时对比当前滚动位置与目标元素的位置,判断滚动方向,再根据方向设置对应偏移量。具体实现如下:
判断滚动方向
获取当前页面的滚动位置currentScrollY,再获取目标元素相对于文档顶部的偏移量targetOffsetTop。如果targetOffsetTop < currentScrollY,说明是向上滚动;反之则为向下滚动。根据方向设置偏移量
- 向上滚动时:header和banner均可见,偏移量需包含两者高度,即
-headerHeight - bannerHeight - 17 - 向下滚动时:header会隐藏,仅banner可见,偏移量只需包含banner高度,即
-bannerHeight - 17
- 修改后的完整代码
document.querySelectorAll('#page-list a[href^="#"]').forEach((anchor) => { anchor.addEventListener("click", function (e) { e.preventDefault(); const targetElement = document.querySelector(this.getAttribute("href")); const headerHeight = document.querySelector("header").offsetHeight; const bannerHeight = document.querySelector(".compare-form__sticky").offsetHeight; if (targetElement) { const currentScrollY = window.scrollY; const targetOffsetTop = targetElement.offsetTop; // 判断滚动方向:目标位置在当前滚动位置上方则为向上滚动 const isScrollUp = targetOffsetTop < currentScrollY; // 根据滚动方向切换偏移量 const offset = isScrollUp ? -headerHeight - bannerHeight - 17 : -bannerHeight - 17; const elementPosition = targetElement.getBoundingClientRect().top; const offsetPosition = elementPosition + window.scrollY + offset; window.scrollTo({ top: offsetPosition, behavior: "smooth", }); } }); });
- 关键逻辑说明
currentScrollY:记录点击锚点时的实时滚动位置targetOffsetTop:目标元素在文档中的顶部偏移量,用于和当前滚动位置对比判断方向isScrollUp:布尔值标记滚动方向,以此动态调整偏移量的计算逻辑
调整后,点击锚点时会自动适配滚动方向设置偏移量,避免header或banner遮挡目标区块的开头。
内容的提问来源于stack exchange,提问作者Marling
相关产品推荐
相关产品推荐

