1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

【コピペ】特定のHTML要素の下部まで画面をスクロールさせる関数

Last updated at Posted at 2024-04-01
export function scrollToElementUnderline(elementId: string, duration: number = 375) {
  const element = document.getElementById(elementId);
  if (element) {
    const rect = element.getBoundingClientRect();
    const isVisible = rect.top >= 0 && rect.bottom <= window.innerHeight;
    if (!isVisible) {
      const startPosition = window.scrollY;
      const endPosition = startPosition + rect.bottom - window.innerHeight;
      const startTime = performance.now();

      const animateScroll = (currentTime: number) => {
        const elapsedTime = currentTime - startTime;
        const progress = Math.min(elapsedTime / duration, 1);
        const scrollPosition = startPosition + (endPosition - startPosition) * progress;
        window.scrollTo(0, scrollPosition);
        if (elapsedTime < duration) {
          requestAnimationFrame(animateScroll);
        }
      };
      requestAnimationFrame(animateScroll);
    }
  }
}

補足

idを指定するstring値を引数に取る
デフォルト引数のdurationはスクロールにかける時間(ms)を指定

1
0
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?