JavaScriptでページトップに戻るための5つの方法(実装から強化まで)

  1. window.scrollToメソッドやdocument.documentElement.scrollTopプロパティを使用して実現する。
function scrollToTop() {
  window.scrollTo(0, 0);
}
  1. 「window.scrollToメソッドとrequestAnimationFrameを組み合わせて、スムーズなスクロール効果を実現する方法」
function smoothScrollToTop() {
  const currentScroll = document.documentElement.scrollTop || document.body.scrollTop;
  if (currentScroll > 0) {
    window.requestAnimationFrame(smoothScrollToTop);
    window.scrollTo(0, currentScroll - (currentScroll / 8));
  }
}
  1. 指定された要素のトップにスクロールするために、scrollIntoViewメソッドを使用します。
function scrollToElementTop(element) {
  element.scrollIntoView({ behavior: 'smooth', block: 'start' });
}
  1. アニメートメソッドを使用してスムーズなスクロール効果を実装します。
function animateScrollToTop(duration) {
  const start = document.documentElement.scrollTop || document.body.scrollTop;
  const target = 0;
  const distance = target - start;
  const startTime = performance.now();
  
  function step() {
    const currentTime = performance.now();
    const elapsed = currentTime - startTime;
    const progress = Math.min(elapsed / duration, 1);
    const easing = function(t) { return t * (2 - t); }; // 缓动函数,例如使用二次方函数
    const position = start + distance * easing(progress);
    
    window.scrollTo(0, position);
    
    if (progress < 1) {
      window.requestAnimationFrame(step);
    }
  }
  
  window.requestAnimationFrame(step);
}
  1. 強化版:ボタン要素を追加し、クリックイベントを結びつけます。
<button id="scrollToTopBtn">回到顶部</button>
document.getElementById('scrollToTopBtn').addEventListener('click', scrollToTop);

function scrollToTop() {
  window.scrollTo({ top: 0, behavior: 'smooth' });
}

これは、ページのトップに戻るための一般的な実装方法の5つの例です。最も基本的なスクロールからトップへの方法から、スムーズなスクロール効果やボタンクリックイベントが追加された高度な方法まであります。特定のニーズに応じて、適切な方法を選択してページのトップに戻る機能を実現することができます。

bannerAds