how to make javascript scrollIntoView smooth?

后端 未结 2 997
面向向阳花
面向向阳花 2020-12-13 17:20

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

scrollToQuestionNode(id) {
        const element = document.get         


        
相关标签:
2条回答
  • 2020-12-13 17:26

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

    For easy implementation use a wrapper like this around the polyfill so the .js polyfill method would be inizialized after loading:

    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'
    });
    
    0 讨论(0)
  • 2020-12-13 17:44

    This might help.

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

    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

    0 讨论(0)
提交回复
热议问题