创建滚动到ID没有jQuery和offsetTop -80px



我希望当用户点击任何前面带有#的链接时,将他们带到HTML代码中具有该ID的同一页面的某个部分。

这个解决了我的问题:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});

现在,因为我有一个80px高的标题,我希望它向下滚动到ID - 80px。

如何将此应用于现有代码?我想继续使用JavaScript。

首先找到元素在页面上的位置,然后使用调整顶部的scrollTo。

注意!这可能行不通,这取决于你的元素定位,固定的,静态的,等等。

const elementTop = (element) => {
let offsetTop = element.offsetTop;
// add offsetTops all the way to <body>
let offsetParent = element.offsetParent;
while(offsetParent) {
offsetTop += offsetParent.offsetTop;
offsetParent = offsetParent.offsetParent;
}
return offsetTop;
};
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
const targetEl = document.querySelector(this.getAttribute('href'));
const targetElTop = elementTop(targetEl);

window.scrollTo({ 
top: targetElTop + 80, // your adjustments 
behavior: 'smooth' 
});
});
});

mdn scrollTomdn offsetParent

最新更新