<button class="go-to-top" onclick="goToTop()"><i class="fas fa-arrow-alt-circle-up"></i></button>
.go-to-top {
position: fixed;
bottom: 10px;
right: 10px;
font-size: 3rem;
opacity: 0;
transition: all 0.2s;
}
goToTop = () => {
window.scrollTo({ top: 0, behavior: "smooth" });
};
동작 원리는 간단하다
1. 버튼을 만든다
2. 버튼의 위치는 오른쪽 하단에 고정시키기위해 positon : fixed , bottom: 10px, right:10px 로 설정한다.
3. 실행될 때 스크롤을 가장 위로(top: 0)으로 가게 만드는 함수goToTop를 만든다. *behavior:"smoot"는 스크롤 액션을 부드럽게 만들어준다.
4. 클릭하면 goToTop 함수가 실행되게 만든다.<button class="go-to-top">
window.addEventListener("scroll",function(){})
window.addEventListener("scroll", function () {
var height = document.documentElement.scrollTop;
}
window.addEventListener("scroll", function () {
var height = document.documentElement.scrollTop;
if (height > 110) {
this.document.querySelector(".go-to-top").style.opacity = 1;
} else {
this.document.querySelector(".go-to-top").style.opacity = 0;
}
});