简体   繁体   中英

scrollIntoView causing entire page to scroll

I want to scroll a div container to center of its scrollable area when a certain event occurs. I am using scrollIntoView to achieve this:

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. 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 . I want to scroll the page after the scrollIntoView animation completes. 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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