스크롤 시 고정헤더 만들기 (html,css,javascript활용)
<nav id="mainNav">
<div class="logo">
<img src="https://media.vlpt.us/images/sueuniya/post/4e688a41-1a20-49b5-a04f-25a1460bf472/logo.png" alt="" class="pink_logo">
</div>
<ul>
<li><a href="">Home</a></li>
<li><a href="">FAQS</a></li>
<li><a href="">Services</a></li>
<li><a href="">About me</a></li>
</ul>
</nav>
<section> section 1 </section>
<section> section 2 </section>
<section> section 3 </section>
body {
font-family: roboto, sans-serif;
}
.logo img {
height: 84px;
transiton: height .4s;
}
.nav-bg{
background:#eee;
}
.txt-white a {
color:#666;
}
nav {
display:flex;
justify-content: space-between;
padding: 0 16px;
position: fixed;
width: 100%;
background:#fff;
border-bottom: 0px solid #9d9d9d;
top:0;
transiton: all .4s;
}
nav ul {
display:flex;
align-items: center;
width: 400px;
justify-content: space-around;
}
nav ul li a {
text-decoration: none;
color: #333;
font-weight: 500;
transition: color .4s;
}
section:nth-of-type(1){
margin-top: 84px;
}
section {
height:300px;
padding: 16px;
font-size: 20px;
}
section:nth-of-type(odd){
background: #fff;
color: #333;
}
section:nth-of-type(even){
background: #eee;
color: #333;
}
window.addEventListener('scroll', function(){
const logo = document.querySelector
('.logo img');
const mainNav = document.getElementById('mainNav');
// if(window.scrollY > 50) 도 사용가능
if(window.pageYOffset > 50){
logo.style.height = "64px";
mainNav.classList.add('nav-bg');
mainNav.classList.add('txt-white');
}else{
logo.style.height = "84px";
mainNav.classList.remove('nav-bg');
mainNav.classList.remove('txt-white');
}
})
- console 창에서 어디 위치에 있는지 알 수 있다
window.addEventListener('scroll', function(){
console.log(window.scrollY)
});