Using scrollIntoView with a fixed position header

前端 未结 8 1130
粉色の甜心
粉色の甜心 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:10

    In case if someone has fixed navbar which hides Header\Title after scrolling, here is the solution (based on @coco puffs's answer and this one):

    let anchorLinks = document.querySelectorAll('a[href^="#"]')
    
    for (let item of anchorLinks) {
      item.addEventListener('click', (e) => {
        let hashVal = item.getAttribute('href')
        let topOfElement = document.querySelector(hashVal).offsetTop - 70
    
        window.scroll({ top: topOfElement, behavior: "smooth" })
        history.pushState(null, null, hashVal)
        e.preventDefault()
      })
    }
    

    In the code 70px are used.

提交回复
热议问题