如何使 javascript scrollIntoView 平滑?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42503599/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:12:25  来源:igfitidea点击:

how to make javascript scrollIntoView smooth?

javascriptcssreactjsscroll

提问by Sahil Sharma

In a react app, I have a method being called to bring a particular node into view as follows.

在 React 应用程序中,我调用了一个方法来将特定节点置于视图中,如下所示。

scrollToQuestionNode(id) {
        const element = document.getElementById(id);
        element.scrollIntoView(false);
}

The scroll happens fine, but the scroll action is a little jerky. How can I make it smooth? I don't see any options which I can give to scrollIntoView for the same.

滚动发生得很好,但滚动动作有点生涩。我怎样才能使它光滑?我没有看到任何可以为 scrollIntoView 提供的选项。

回答by lavish

This might help.

这可能会有所帮助。

From MDN documentation of scrollIntoView You can pass in option instead of boolean.

从 scrollIntoView 的 MDN 文档中,您可以传入选项而不是布尔值。

scrollIntoViewOptions Optional
A Boolean or an object with the following options:
{
  behavior: "auto"  | "instant" | "smooth",
  block:    "start" | "center" | "end" | "nearest",
  inline:    "start" | "center" | "end" | "nearest",
}

So you can simply pass parameter like this.

所以你可以像这样简单地传递参数。

scrollToQuestionNode(id) {
  const element = document.getElementById(id);
  element.scrollIntoView({ block: 'end',  behavior: 'smooth' });
}

Reference: https://developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

参考:https: //developer.mozilla.org/en/docs/Web/API/Element/scrollIntoView

回答by metamagikum

For multibrowser support use the smooth-scroll-polyfill from here

对于多浏览器支持,请使用此处的平滑滚动polyfill

For easy implementation use a wrapperlike this around the polyfillso the .jspolyfillmethod would be inizialized after loading:

为了便于实现,请使用wrapper类似polyfill这样的.jspolyfill方法,以便在加载后初始化方法:

https://codepen.io/diyifang/embed/MmQyoQ?height=265&theme-id=0&default-tab=js,result&embed-version=2

https://codepen.io/diyifang/embed/MmQyoQ?height=265&theme-id=0&default-tab=js,result&embed-version=2

Now this should work cross browser:

现在这应该可以跨浏览器工作:

document.querySelector('.foo').scrollIntoView({
  behavior: 'smooth'
});