Using scrollIntoView with a fixed position header

前端 未结 8 1111
粉色の甜心
粉色の甜心 2020-12-08 01:50

I have a site with a header set to position: fixed. On one of my pages, I use scrollIntoView(true) on an element. My problem is that when scr

相关标签:
8条回答
  • 2020-12-08 02:27

    Try the following. It works well for me:

      const headerHeight = 50; /* PUT HEADER HEIGHT HERE */
      const buffer = 25; /* MAY NOT BE NEEDED */
      const scrollToEl = document.querySelector("#YOUR-ELEMENT-SELECTOR");
    
      const topOfElement = window.pageYOffset + scrollToEl.getBoundingClientRect().top - headerHeight - buffer;
      window.scroll({ top: topOfElement, behavior: "smooth" });
    
    0 讨论(0)
  • 2020-12-08 02:30

    The following code yields a smooth scroll to the top of the element with an offset for fixed header:

    var topOfElement = document.querySelector('#targetElement').offsetTop - XX;
    window.scroll({ top: topOfElement, behavior: "smooth" });
    

    Where XX is the height of your fixed header.

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