scrollIntoViewでスムーススクロールを実装したサンプル

top

go to #bottom

sample

sample

sample

sample

sample

sample

sample

bottom

go to #top
<style>p { margin-bottom: 200px; }</style>
<h1 id="top">top</h1>
<a href="#bottom">go to #bottom</a>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<p>sample</p>
<h2 id="bottom">bottom</h2>
<a href="#top">go to #top</a>
const links = document.querySelectorAll('a[href^="#"]')

links.forEach((el) => {
  el.addEventListener('click', (e) => {
    e.preventDefault()
    const href = el.getAttribute('href')
    const target = document.getElementById(href.replace('#', ''))
    target.scrollIntoView({
      behavior: 'smooth'
    })
  })
})

元記事を表示する