반응형
안녕하세요. 오늘은 화면을 스크롤 시 상단 부분을 바뀌는 부분을 JS로 구현해보겠습니다.
SETTING
<body>
<header class="header">
<div>
<a href="#" class="text_active">Home</a>
</div>
<ul class="ul">
<li>
<a href="#" class="text_active">안녕하세요</a>
</li>
<li>
<a href="#" class="text_active">초보개발자</a>
</li>
<li>
<a href="#" class="text_active">청춘고양이</a>
</li>
</ul>
</header>
<main>
<div>안녕하세요</div>
<div>JS를 통해</div>
<div>상단</div>
<div>화면을</div>
<div>변경해</div>
<div>보겠습니다.</div>
</main>
</body>
.header {
align-items: center;
width: 100vw;
background-color: #111111;
border-bottom: 3px solid #666665;
backdrop-filter: blur(5px);
display: flex;
flex-direction: row;
justify-content: space-between;
font-size: 1.5rem;
padding-bottom: 2rem;
padding-top: 2rem;
position: fixed;
z-index: 1;
}
.header > div{
padding-left: 3vw;
}
.ul {
align-items: center;
display: flex;
flex-direction: row;
justify-content: center;
}
.ul >li > a {
padding-right: 5vw;
}
a:link, a:visited {
color: #e1e1e9;
text-decoration: none;
font-weight: bold;
}
body > main {
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
max-height: 100vh;
max-width: 100vw;
height: 100vh;
position: relative;
padding-top: 6.25rem;
background-color: #111111;
}
main > div{
padding-bottom: 2rem;
color: #e1e1e9;
}
JS
상단을 잡으려면 scrollY를 이용해서 위에 좌표를 알아내면 됩니다.
110일 때 값을 변경시켜보겠습니다.
const header = document.querySelector('#header');
const textActive = document.querySelectorAll('.text_active');
window.addEventListener('scroll', () => {
//scrollY 상단 위치의 좌표 값을 알아 낼 수 있음.
let top = window.scrollY;
console.log(top);
if(top>110) {
//classList.add : html class 속성에 값을 넣어준다.
//ex) 현재 class ="header" -> class = "header active"
//css에서 표현으로 띄우기는 .을 이용한다.
//가령 header active = .header.active로 선택자 표시 가능
header.classList.add('active')
//각각의 텍스트에 값을 넣어주기 위해 for문 사용
for(let i=0;i<textActive.length;i++){
textActive[i].setAttribute('style', 'color : blue');
}
//상단 좌표 값이 110이 아니면 원래화면으로 복구
} else{
header.classList.remove('active');
for(let i=0;i<textActive.length;i++){
textActive[i].setAttribute('style', 'color : #e1e1e9');
}
}
});
구현
반응형
'JS' 카테고리의 다른 글
가위바위보 (0) | 2022.06.02 |
---|---|
lotto JS (0) | 2022.06.02 |
Timer (0) | 2022.05.28 |
Text Effect (0) | 2022.05.27 |
NodeList (0) | 2022.05.25 |