【问题标题】:scrollIntoView causing entire page to scrollscrollIntoView 导致整个页面滚动
【发布时间】:2020-05-12 14:20:39
【问题描述】:

当某个事件发生时,我想将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 动画完成后滚动页面。有没有办法做到这一点?

【问题讨论】:

    标签: javascript html css google-chrome


    【解决方案1】:

    尝试包装它,使其在事件循环的下一轮执行:

    setTimeout(()=>
      window.scrollTo(0, 0);
    , 0);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-03-18
      • 2021-06-08
      • 2014-12-10
      相关资源
      最近更新 更多