<nav>
<ul class="menus">
<li class="menu"><a class="btn" data-sec="section_1" href="#">S1</a></li>
<li class="menu"><a class="btn" data-sec="section_2" href="#">S2</a></li>
<li class="menu"><a class="btn" data-sec="section_3" href="#">S3</a></li>
<li class="menu"><a class="btn" data-sec="section_4" href="#">S4</a></li>
<li class="menu"><a class="btn" data-sec="section_5" href="#">S5</a></li>
</ul>
</nav>
<section id="section_1">
<h1># Section 1</h1>
</section>
<section id="section_2">
<h1># Section 2</h1>
</section>
<section id="section_3">
<h1># Section 3</h1>
</section>
<section id="section_4">
<h1># Section 4</h1>
</section>
<section id="section_5">
<h1># Section 5</h1>
</section>
/* RESET */
@import url('https://fonts.googleapis.com/css2?family=Bebas+Neue&display=swap');
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
ul {
list-style: none;
}
a {
color: #000000;
text-decoration: none;
}
/* FUNDAMENTAL */
body {
background-color: #fcfcfc;
font-family: 'Bebas Neue', Arial, Helvetica, sans-serif;
position: relative;
}
nav {
position: fixed;
z-index: 100;
width: 100%;
top: 0;
text-align: center;
}
nav .menus {
margin-top: 15px;
display: inline-block;
}
nav .menus .menu {
color: black;
font-size: 1em;
display: inline;
margin-right: 5px;
vertical-align: middle;
}
nav .menus .menu a {
background-color: #fcfcfc;
color: #999;
width: 25px;
height: 25px;
padding-top: 5px;
display: inline-block;
border-radius: 50%;
}
nav .menus .menu:last-child {
margin-right: 0;
}
section {
position: relative;
background-color: coral;
width: 100%;
height: 100vh;
}
section h1 {
position: absolute;
color: #ffffff;
letter-spacing: 1px;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
font-size: 2em;
}
#section_1 {
background-color: skyblue;
}
#section_2 {
background-color: coral;
}
#section_3 {
background-color: darkcyan;
}
#section_4 {
background-color: lightslategrey;
}
#section_5 {
background-color: lightsteelblue;
}
'use strict';
const menus = document.querySelector('.menus');
// 1. 조상 요소로부터 버튼에게 이벤트 위임
menus.addEventListener('click', function(e) {
e.preventDefault();
const curTarget = e.target;
if (!curTarget.classList.contains('btn')) return;
// 2. 버튼의 해당 섹션 id값을 가져와 일치하는 DOM 요소를 변수 할당
const currentSection = document.querySelector(`#${curTarget.dataset.sec}`);
// 3. 원하는 위치로 스크롤링
window.scrollTo({
top: currentSection.getBoundingClientRect().top + window.pageYOffset,
behavior: 'smooth',
})
})
This Pen doesn't use any external CSS resources.
This Pen doesn't use any external JavaScript resources.