scroll-behavior: smooth;とJavaScriptの併用例

Go to LAST

TEST

TEST

TEST

TEST

TEST

TEST

TEST

TEST

TEST

TEST

LAST

Go to TOP
<a href="#last">Go to LAST</a>
<p>TEST</p>
<p>TEST</p>
<!-- 略 -->
<p>TEST</p>
<p>TEST</p>
<p id="last">LAST</p>
<a href="#top">Go to TOP</a>
html {
  scroll-behavior: smooth;
}
const smoothScroll = document.querySelectorAll('a[href^="#"]');
smoothScroll.forEach((el) => {
  el.addEventListener('click', (e) => {
    e.preventDefault();
    const href = el.getAttribute('href');
    const targetElement = document.getElementById(href.replace('#', ''));
    const rect = targetElement.getBoundingClientRect().top;
    const offset = window.pageYOffset;
    window.scrollTo({
      top: rect + offset,
      behavior: 'smooth',
    });
  });
});

元記事を表示する