Using scrollIntoView with a fixed position header

前端 未结 8 1146
粉色の甜心
粉色の甜心 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条回答
  •  旧时难觅i
    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" });
    

提交回复
热议问题