简体   繁体   English

平滑滚动以锚定滚动行为,但高于100px

[英]Smooth croll to anchor with scroll-behavior, but 100px above

I'm trying to do smooth scroll effect to anchors on my page, but i need to scroll it 100px above because of sticky header. 我正在尝试对页面上的锚点进行平滑滚动效果,但是由于页眉发粘,我需要将其滚动100px以上。 Don't want to use JQuery there. 不想在那里使用JQuery。 I have tried to add pseudoclass to block with anchor like this: 我试图添加伪类来阻止锚,如下所示:

div:target:before {
  content: '';
  display: block;
  height: 100px;
  margin-top: -100px;
  visibility: hidden;
}

This didn't work, it overlaying block above. 这没有用,它覆盖了上面的块。 Then i've tried to scroll it by event listener: 然后我尝试通过事件监听器滚动它:

window.addEventListener("hashchange", function () {
  window.scrollTo(window.scrollX, window.scrollY - 100);
});

It's working only without scroll-behavior property. 它仅在没有滚动行为属性的情况下工作。 Is there any solution? 有什么解决办法吗? Thank you! 谢谢!

try replacing the 尝试更换

window.scrollTo(...)

with

document.getElementById('yourElemId').scrollIntoView({behavior: "smooth", block: "end"});

the yourElemId is the id of the element with the anchor. yourElemId是具有锚点的元素的ID。

Here is the documentation for scrollIntoView 这是scrollIntoView的文档

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM