반응형
250x250
Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 | 31 |
Tags
- 애니메이션
- Animation
- insertAdjacentHTML
- css
- NodeList
- For
- 스크롤
- swiper
- classList
- scrollevent
- localstorage
- scroll
- html
- width
- input
- scrollY
- 이벤트리스너
- 반복문
- Sticky
- mousemove
- 확장성
- JavaScript
- getBoundingClientRect
- React
- addEventListener
- NAV
- pointermove
- swiperjs
- forEach
- Hover
Archives
- Today
- Total
ZeroToHunnit Coding
[Javascript] 마우스따라 움직이는 bar 본문
728x90
반응형
위와 같이 각 번호에 마우스를 올리면 밑에 바가 자연스럽게 옆으로 움직이는 애니메이션을 만들어보았다.
HTML
<div class="section">
<ul class="row">
<li class="content">1번임</li>
<li class="content">2번임</li>
<li class="content">3번임</li>
<li class="content">4번임</li>
<li class="content">5번임</li>
<div class="line"></div>
</ul>
</div>
CSS
.row{
width: 100%;
display: flex;
justify-content: center;
align-items: center;
margin-top: 300px;
position: relative;
}
li{
width: 250px;
height: 200px;
display: flex;
align-items: center;
justify-content: center;
font-size: 40px;
cursor: pointer;
transition: all 0.3s;
}
li:hover{
color: crimson;
}
.line{
position: absolute;
height: 20px;
background: crimson;
bottom: 0;
transition: left 0.3s;
}
자바스크립트로 left값을 조절할 것이기 때문에 transition을 left값에 부여했다.
JAVASCRIPT
for(let i = 0; i < document.querySelectorAll('.content').length; i++){
document.querySelectorAll('.content')[i].addEventListener('mouseover',function(){
let contentX = document.querySelectorAll('.content')[i].getBoundingClientRect().x;
let contentWidth = document.querySelectorAll('.content')[i].getBoundingClientRect().width;
document.querySelector('.line').style.left = `${contentX}px`;
document.querySelector('.line').style.width = `${contentWidth}px`;
});
document.querySelectorAll('.content')[i].addEventListener('mouseout',function(){
document.querySelector('.line').style.width = 0;
})
}
for반복문으로 li에 마우스를 올리면 line의 left값과 width값을 li와 동일하게 조절되도록 코드를 짰다.
getboundingClientRect().x 를 하면 요소의 x좌표 값을, width를 하면 요소의 width값을 찾아준다.
찾은 x좌표의 값과 width값을 line의 left와 width의 css에 부여하는 방식으로 했다.
그리고 li에서 마우스가 나가면 width만 0으로 만들고 left값은 그대로 놔두었다.
위의 것을 잘 이용하면 평소에 nav바 만들 때 이쁘게 구현할 수 있을 것이다.
728x90
반응형
'JAVASCRIPT' 카테고리의 다른 글
[Javascript] 아코디언 메뉴 만들기 (0) | 2024.02.03 |
---|---|
[Javascript] 스크롤 내리면 사라지고 스크롤 올리면 나타나는 navbar (0) | 2024.02.01 |
[Javascript] 데이터로 책 리스트 보여주기 (2) | 2024.01.26 |
[Javascript] 확장성있게 모달창 띄우기 (0) | 2024.01.24 |
[Javascript] 스크롤에 따라 박스 크기, 글자 크기, 위치 조정하기 (2) | 2024.01.22 |