🌈 클릭 한 번으로, 맨 위로 올라가는 ⬆ 버튼의 기능을 구현해보자
- 메인 html 파일에 구글에서 제공하는 아이콘 웹사이트 링크를 걸어준다
// 구글 아이콘 링크
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
// <head> 태그 안에 <script defer> 아래 줄에 넣으면 된다
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>welcome</title>
<link rel="stylesheet" type="text/css" href="style.css">
<script defer src="./main.js"></script>
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Montserrat:ital,wght@0,200;0,400;0,500;0,600;0,800;0,900;1,200;1,400;1,500;1,600;1,800;1,900&display=swap" rel="stylesheet">
<link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100;300;400;500;700;900&display=swap" rel="stylesheet">
</head>
- body 태그 안에 button id 값을 부여하고 아이콘 생성을 위한 i 태그와 span 태그를 만듭니다
The <i> and <span> elements are widely used to add icons.
<body>
<button id="btnScrollToTop">
<i class="materials-icons"><span class="material-icons">arrow_upward</span></i>
</button>
- CSS 파일로 넘어가서 꾸며줍니다
#btnScrollToTop {
position: fixed;
right: 10px;
bottom: 10px;
width: 50px;
height: 50px;
border-radius: 50%;
background: rgb(156, 185, 97);
box-shadow: 0 0 10px rgba(0, 0, 0, 0.25);
color: white;
border: none;
outline: none;
cursor: pointer;
}
#btnScrollToTop:active {
background: green;
}
- 자바스크립트 파일로 넘어가서 아래 코드를 작성합니다
const btnScrollToTop = document.querySelector("#btnScrollToTop");
btnScrollToTop.addEventListener("click", function () {
// window.scrollTo(0, 0); left and top
window.scrollTo({
left: 0,
top: 0,
behavior: "smooth"
})
})
참고 영상: https://www.youtube.com/watch?v=FK5DEa1Hvco