简体   繁体   English

scrollIntoView 导致整个页面滚动

[英]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);

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

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