【发布时间】:2021-06-09 09:44:06
【问题描述】:
当我单击将我向下滚动到某个部分的链接时,我需要添加 -100px 的偏移量。我已经设法让我的滚动平滑,但我不能让它用 offsetY 滚动。
这是我的 js 代码:
const links = document.querySelectorAll("a");
for (const link of links) {
link.addEventListener("click", clickHandler);
}
function clickHandler(e) {
e.preventDefault();
const href = this.getAttribute("href");
const offsetTop = document.querySelector(href).offsetTop;
scroll({
top: offsetTop,
behavior: "smooth",
});
}
...这是我的html:
<a href ="#mysection">Go to section </a>
<p>this is some lorem</p>
<p>this is some lorem</p>
<p>this is some lorem</p>
<div id ="mysection"> The section that appears when i click on the anchor. I want an offset on this div so that when i click on anchor, it wil scroll me at the beggining of this section </div>
【问题讨论】:
-
offsetTop -= 100;? -
你不能使用 href 作为选择器。你需要的是一个属性选择器:
`[href="${href}"]`. -
@Teemu 属性选择器不起作用 :(
-
@Liam offsetTop -=100 不起作用
-
控制台说什么?有什么错误吗?
标签: javascript smooth-scrolling