구글링을 하면서 어떤 태그를 누르면 스크롤이 자동으로 부드럽게 이동하는 smooth scroll을 검색을 하는데 따라하기가 되게 버거운 것들이 많더라고요. 그래서 제 생각에 제일 간단히 구현할 수 있는 코드를 가지고 와봤습니다. (제가 구현을 자주 하는 경우가 있어 정리하는 것도 있구요.)
기본적으로 세팅을 해야겠죠? 폴더를 하나 만들고 그 폴더에 index.html 파일을 만들고 아래와 같이 세팅하였습니다.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
.items {
display: flex;
justify-content: center;
align-items: center;
background-color: palegreen;
width: 100%;
height: 600px;
margin-top: 30px;
font-size: 30px;
font-weight: 700;
}
nav {
display: flex;
justify-content: space-between;
width: 100%;
}
nav .links {
width: 150px;
height: 50px;
background-color: peru;
text-align: center;
line-height: 50px;
font-weight: 700;
}
</style>
</head>
<body>
<nav>
<div class="links" id="link1">To the item1</div>
<div class="links" id="link2">To the item2</div>
<div class="links" id="link3">To the item3</div>
<div class="links" id="link4">To the item4</div>
</nav>
<div class="items" id="item1">This is item1</div>
<div class="items" id="item2">This is item2</div>
<div class="items" id="item3">This is item3</div>
<div class="items" id="item4">This is item4</div>
<script
src="https://code.jquery.com/jquery-3.3.1.js"
integrity="sha256-2Kok7MbOyxpgUVvAk/HJ2jigOSYS2auK4Pfzbm7uH60="
crossorigin="anonymous"></script>
</body>
</html>
이렇게 세팅을 하고 index.html을 브라우저로 열면, 대충 이런 화면이 나옵니다.
그리고 나서, 아래의 Javascript 코드를 </body> 태그 바로 위에 작성해주세요.
<script>
$('#link2').on('click', function() { //id가 link2가 클릭되면 아래의 함수를 실행.
$('html').animate({
scrollTop: $("#item2").offset().top, // id가 item2인 element의 top 값 만큼,
}, 800); // 0.8초 동안 이동(그래서 부드럽게 이동하게 됩니다.)
})
</script>
그리고 나서 index.html에서 link2라는 id를 가진 녀석을 누르면 item2의 윗부분이 브라우저의 화면에 닿을 때까지 부드럽게 이동하게 됩니다.