[英]scrollIntoView causing entire page to scroll
I want to scroll a div
container to center of its scrollable area when a certain event occurs.当某个事件发生时,我想将
div
容器滚动到其可滚动区域的中心。 I am using scrollIntoView
to achieve this:我正在使用
scrollIntoView
来实现这一点:
const target = document.getElementById('target-id');
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
However, this is causing the entire page to scroll up as well.但是,这也会导致整个页面向上滚动。 This seems to be a bug in Chrome as highlighted by this post.
正如这篇文章所强调的,这似乎是 Chrome 中的一个错误。 However, I am trying to negate its effect by scrolling the page to top every time it scrolls.
但是,我试图通过每次滚动时将页面滚动到顶部来否定它的效果。
const target = document.getElementById('target-id');
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
window.scrollTo(0, 0);
But this doesn't work as the container doesn't scroll at all.但这不起作用,因为容器根本不滚动。 I believe this is because I am immediately trying to scroll up the entire page after calling
scrollIntoView
.我相信这是因为我在调用
scrollIntoView
后立即尝试向上滚动整个页面。 I want to scroll the page after the scrollIntoView
animation completes.我想在
scrollIntoView
animation 完成后滚动页面。 Is there a way to achieve this?有没有办法做到这一点?
Try wrapping it so that it executes on the next turn of the event loop:尝试包装它,使其在事件循环的下一轮执行:
setTimeout(()=>
window.scrollTo(0, 0);
, 0);
You can use the parameters that are defined for scrollIntoView().您可以使用为 scrollIntoView() 定义的参数。
scrollIntoView documentation: scrollIntoView 文档:
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollIntoView
Follow this link for solution: https://thewebdev.info/2022/04/21/how-to-fix-scrollintoview-causing-the-whole-page-to-move-with-javascript/#:~:text=move%20with%20JavaScript%3F-,To%20fix%20scrollIntoView()%20causing%20the%20whole%20page%20to%20move,block%20set%20to%20'nearest'%20.按照此链接获取解决方案: https://thewebdev.info/2022/04/21/how-to-fix-scrollintoview-causing-the-whole-page-to-move-with-javascript/#:~:text= move%20with%20JavaScript%3F-,To%20fix%20scrollIntoView()%20causing%20the%20whole%20page%20to%20move,block%20set%20to%20'nearest'%20.
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.