使用固定 header 平滑 javascript 滚动

Smooth javascript scrolling with a fixed header

美好的一天。在网站上为 javascript 实现了平滑滚动。一切正常,页面本身严格滚动到所需部分的开头。但是由于我有固定的header,反而占了一部分的review。问题是如何把这个header的高度加上滚动条

js

  const anchors = document.querySelectorAll('.scroll-href')

  anchors.forEach(item => {
    item.addEventListener('click', (e) => {
      e.preventDefault()

      const blockID = item.dataset.scroll

      document.getElementById(blockID).scrollIntoView({
        behavior: 'smooth',
        block: 'start'
      })

    })
  })

hmtl

<header class="header">
 Some content
</header>

<a href="#" data-scroll="reviews-section">Scroll to reviews</a>
<a href="#" data-scroll="services-section">Scroll to services</a>
<a href="#" data-scroll="cases-section">Scroll to cases</a>
<a href="#" data-scroll="footer-section">Scroll to footer</a>

<section class="reviews" id="reviews-section">Some content</section>
<section class="services" id="services-section">Some content</section>
<section class="reviews" id="cases-section">Some content</section>
<section class="reviews" id="footer-section">Some content</section>

css

.header
  padding: 10px 0px
  position: fixed
  top: 0
  left: 0
  width: 100%
  background-color: #050505
  z-index: 10

Link 到站点 https://mpleader.pro/(移动设备上可能存在错误)

没有滚动的剖面图

带滚动的剖面图

为您的版块设置 scroll-margin-top

section{
 scroll-margin-top: 10px; /* normally that would be equal to your header's height */
}