scrollIntoViewのサンプル

<header class="navbar">navbar</header>
<main class="content">
  <button id="go-to-bottom">下端へ移動</button>
  <button id="go-to-top">上端へ移動</button>
</main>
.navbar {
  display: flex;
  justify-content: center;
  align-items: center;
  position: sticky;
  top: 0;
  height: 50px;
  border-bottom: 2px solid #333;
}
.content {
  position: relative;
  height: 2000px;
  padding-top: 50px;
}
#go-to-bottom {
  position: absolute;
  top: 10px;
}
#go-to-top {
  position: absolute;
  bottom: 10px;
}
const goToTop = document.getElementById('go-to-top')
const goToBottom = document.getElementById('go-to-bottom')

goToBottom.addEventListener('click', () => {
  goToTop.scrollIntoView({ block: 'start', behavior: 'smooth' })
})

goToTop.addEventListener('click', () => {
  goToBottom.scrollIntoView({ block: 'end', behavior: 'smooth' })
})

元記事を表示する