我想在发生某个事件时将div
容器滚动到其可滚动区域的中心。我正在使用scrollIntoView
实现这一目标:
const target = document.getElementById('target-id');
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
但是,这也会导致整个页面向上滚动。正如this帖子所强调的,这似乎是Chrome中的错误。但是,我试图通过在每次滚动时将页面滚动到顶部来抵消其效果。
const target = document.getElementById('target-id');
target.scrollIntoView({ behavior: 'smooth', block: 'center' });
window.scrollTo(0, 0);
但是这不起作用,因为容器根本不滚动。我相信这是因为调用scrollIntoView
之后,我立即尝试向上滚动整个页面。我想在scrollIntoView
动画完成后滚动页面。有没有办法做到这一点?
答案 0 :(得分:0)
尝试包装它,以便它在事件循环的下一轮执行:
setTimeout(()=>
window.scrollTo(0, 0);
, 0);