admin管理员组文章数量:1394133
I am trying to scroll elements into view using the .scrollIntoView()
function in JavaScript.
section.reference.value.scrollIntoView(
{
behavior: "smooth",
"block": "start",
"inline": "start"
}
);
It almost works perfectly, it scrolls everything necessary to show the element, except it always cuts it off by about 10px, and I don't think there is an option to give it an offset when scrolling.
Does anyone know how to do this?
I am trying to scroll elements into view using the .scrollIntoView()
function in JavaScript.
section.reference.value.scrollIntoView(
{
behavior: "smooth",
"block": "start",
"inline": "start"
}
);
It almost works perfectly, it scrolls everything necessary to show the element, except it always cuts it off by about 10px, and I don't think there is an option to give it an offset when scrolling.
Does anyone know how to do this?
Share Improve this question edited Jul 31, 2022 at 7:29 Ouroborus 16.9k8 gold badges40 silver badges65 bronze badges asked Jul 31, 2022 at 7:23 Jamzy01Jamzy01 3376 silver badges18 bronze badges 02 Answers
Reset to default 4To use JavaScript scrollIntoView to do smooth scroll with offset, you can call scrollTo with an object that has the top and behavior properties.
const element = document.getElementById("targetElement"); // Your target element
const headerOffset = 45;
const elementPosition = element.getBoundingClientRect().top;
const offsetPosition = elementPosition + window.pageYOffset - headerOffset;
window.scrollTo({
top: offsetPosition,
behavior: "smooth",
});
I fixed this by just creating a temporary element inside that element, and moving it using relative positioning to account for my own offset, then deleting it right after.
本文标签: javascriptelementscrollIntoView cuts off the topStack Overflow
版权声明:本文标题:javascript - element.scrollIntoView cuts off the top - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744577381a2613707.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论