scrollTo를 이용한 맨 위로 / 맨 아래로 버튼 만들기

2022. 7. 22. 16:26javaScript

window.scrollTo()

문서의 지정한 위치로 스크롤 되는 함수

사용법

// window.scrollTo(x좌표, y좌표);
window.scrollTo(0, 0);

// window.scrollTo({top:x좌표, left:y좌표, behavior:''})
window.scrollTo({top:0, left:0, behavior:'smooth'})

 

 

맨 위로 /  맨 아래로 가기

HTML / CSS

<style>
  .top, .bottom {
    width: 24px;
    height: 24px;
    curser: pointer;
  }
  .top {background: orange;}
  .bottom {background: blue;}
</style>

<div>
  <div class="top"></div>
  <div class="bottom"></div>
</div>

JS

// 맨 위로 가기
$('.top').click(function(){
  window.scrollTo({top:0, left:0, behavior:'smooth'})
});

// 맨 아래로 가기
$('.bottom').click(function(){
  let bottom = document.body.scrollHeight;
  window.scrollTo({top:bottom, left:0, behavior:'smooth'})
});
  • scrollHeight : 눈에 보이지 않는 영역까지 포함한 전체 contents + padding의 높이값
  • offsetHeight : 눈에 보이는 contents + padding + border+ scrollbar의 높이값
  • clientHeight :  눈에 보이는 contents + padding의 높이값

즉, window의 top에서 body의 전체 높이값만큼 스크롤을 이동시키는 것은 맨 아래로 내리는 것과 동일하므로 맨 아래로 가기의 함수로 사용할 수 있다

 

 

 

 

참고사이트

http://iamdustan.com/smoothscroll/

 

Smooth Scroll behavior polyfill

The Scroll Behavior specification has been introduced as an extension of the Window interface to allow for the developer to opt in to native smooth scrolling. Check the repository on GitHub or download the polyfill as an npm module.

iamdustan.com

https://blogpack.tistory.com/706