반응형
Notice
Recent Posts
Recent Comments
Link
250x250
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | 5 | ||
6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 | 15 | 16 | 17 | 18 | 19 |
20 | 21 | 22 | 23 | 24 | 25 | 26 |
27 | 28 | 29 | 30 |
Tags
- SQLD
- Hover
- insertAdjacentHTML
- swiperjs
- React
- css
- mousemove
- scrollY
- Sticky
- html
- ADsP
- 이벤트리스너
- 스크롤
- localstorage
- input
- For
- swiper
- pointermove
- getBoundingClientRect
- scrollevent
- classList
- addEventListener
- Animation
- 가로스크롤
- NodeList
- 반복문
- JavaScript
- forEach
- scroll
- 애니메이션
Archives
- Today
- Total
ZeroToHunnit Coding
[Javascript] 특정 위치에서 div 속성 바꾸기 본문
728x90
반응형
이렇게 특정 위치에 도달하면 div의 속성을 바꾸고 특정 위치를 벗어나면 속성을 원래대로 돌리는 애니메이션을 만들었다.
HTML
<div class="section">
<div class="left">
<p>여기는 고정!</p>
</div>
<div class="right">
<div class="right-left">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div class="right-right">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
</div>
</div>
왼쪽은 고정, 오른쪽에 여러개의 box를 만들어두었다.
CSS
.section{
width: 100%;
height: 500vh;
margin-top: 500px;
display: flex;
}
.left{
position: sticky;
top: 0;
width: 50%;
height: 100vh;
}
.left p{
text-align: center;
font-size: 60px;
margin-top: 300px;
}
.right{
width: 50%;
display: flex;
}
.right-left,
.right-right{
width: 50%;
}
.right-left .box,
.right-right .box{
width: 300px;
height: 300px;
border: 5px solid black;
margin-top: 100px;
transition: all 0.3s;
}
.right-right .box:first-child{
margin-top: 200px;
}
.active{
background: black;
}
active라는 클래스를 미리 만들어 놓고 자바스크립트로 클래스를 넣고 뺄 예정이다.
Javascript
window.addEventListener('scroll', function () {
for (let i = 0; i < document.querySelectorAll('.box').length; i++) {
if (document.querySelectorAll('.box')[i].getBoundingClientRect().top <= 500 && document.querySelectorAll('.box')[i].getBoundingClientRect().top >= 200) {
document.querySelectorAll('.box')[i].classList.add('active');
} else {
document.querySelectorAll('.box')[i].classList.remove('active');
}
}
})
스크롤 이벤트리스너를 사용해서 for 반복문을 사용해주었다. getBoundingClientRect().top는 div의 꼭대기 위치의 화면상의 scroll 값을 구해준다. 그래서 200 ~ 500사이에 위치할 때 active클래스를 추가해주고 벗어나면 클래스를 제거하는 코드를 짰다.
이번 코드를 짜면서 getboundingClientRect().top이라는 코드를 알게 되어서 이 또한 유용하게 많이 쓰일 수 있을 거라고 생각한다.
728x90
반응형
'JAVASCRIPT' 카테고리의 다른 글
[Javascript] 타이핑 애니메이션 (2) | 2024.01.01 |
---|---|
[Javascript] 커서따라 3d느낌으로 움직이는 카드 (0) | 2023.12.31 |
[Javascript] 특정 위치가 되면 가로 스크롤하기 (1) | 2023.12.28 |
[Javascript] 스크롤하면 메인 visual 크기 변경 (0) | 2023.12.27 |
[JAVASCRIPT] 마우스커서 따라 움직이는 효과 (0) | 2023.12.26 |