How to scroll HTML page to given anchor?

后端 未结 17 2065
醉梦人生
醉梦人生 2020-11-22 08:55

I’d like to make the browser to scroll the page to a given anchor, just by using JavaScript.

I have specified a name or id attribute in my

17条回答
  •  再見小時候
    2020-11-22 09:25

    2018-2020 Pure js:

    There is a very convenient way to scroll to the element:

    el.scrollIntoView({
      behavior: 'smooth', // smooth scroll
      block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
    })
    

    But as far as I understand he does not have such good support as the options below.

    Learn more about the method.


    If it is necessary that the element is in the top:

    const element = document.querySelector('#element')
    const topPos = element.getBoundingClientRect().top + window.pageYOffset
    
    window.scrollTo({
      top: topPos, // scroll so that the element is at the top of the view
      behavior: 'smooth' // smooth scroll
    })
    

    Demonstration example on Codepen


    If you want the element to be in the center:

    const element = document.querySelector('#element')
    const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
    const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
    
    window.scroll({
      top: rect.top + rect.height / 2 - viewHeight / 2,
      behavior: 'smooth' // smooth scroll
    });
    

    Demonstration example on Codepen


    Support:

    They write that scroll is the same method as scrollTo, but support shows better in scrollTo.

    More about the method

提交回复
热议问题