scrollTo를 이용한 맨 위로 / 맨 아래로 버튼 만들기
2022. 7. 22. 16:26ㆍjavaScript
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
'javaScript' 카테고리의 다른 글
tab 클릭 시 css 변경 (0) | 2022.10.24 |
---|---|
JS로 별모양 찍기 (for문) (0) | 2022.08.25 |
div로 progress bar 만들기 (scroll indicator) (0) | 2022.08.02 |
버튼 필터링 + 검색어 입력 후 검색버튼 클릭(select option 선택 후 주제에 따라 검색하는 기능) javaScript (0) | 2022.04.25 |
스크롤 이벤트_fade In(페이드인)(vanilla js + css) (0) | 2022.04.04 |