본문 바로가기
Js&React 실습/JSprac

[JS] 드롭다운 구현하기

by sweesweet 2022. 7. 5.

이전에는 연습한것들을 버튼에 링크를 달아서 했었는데, 모양새가 조금 그런것 같아서 드롭다운으로  바꿔보았다.

이전 연습들과 마찬가지로 처음 구현해보는거였는데, 다른사람들꺼를 봤을 땐 js없이 가능 한것 같던데, 코드를 아무리봐도 알수가 없었다. 그래서 setTimeOut과 transition을 이용해서 스르륵 나타내는 효과를 주었다

 

전체 js코드

const previewUl = document.querySelector('.preview__ul'); // '연습한 것 중에 하나' 부분
const pracList = document.querySelector('.prac__list'); //'찐 리스트'
const toggle = document.querySelector('.toggle');// 옆에 삼각형
previewUl.addEventListener('click', () => {// 연습한 것 중에 하나를 클릭했을 때 이벤트
  pracList.style.display = 'block'; //list block하면서 
  toggle.style.transform = 'rotate(180deg)';//toggle 180도 돌기
  toggle.style.top = 'calc(50% - 12px)';//위치를 안 돈 토글과 맞추기 위해서 -12px
  let time = 0; // 딜레이가 발생해서 시간을 변수로 선언하였다
  for (let el of pracList.children) {
    setTimeout(() => {
      el.style.height = '70px';
      el.style.opacity = '1';
    }, time);
    time += 100;
  }
});
pracList.addEventListener('mouseleave', () => {
  toggle.style.transform = 'translateY(-50%) rotate(0deg)';
  toggle.style.top = '50%';
  let time = 0;
  for (let i = pracList.children.length - 1; i >= 0; i--) {
    setTimeout(() => {
      pracList.children[i].style.height = '0';
      pracList.children[i].style.opacity = '0';
    }, time);
    time += 100;
  }
  setTimeout(() => {
    pracList.style.display = 'none';
  }, 500);//<-이부분에 골치아팠음

  //
});
// 왜 mouseout 안쓰냐? -> 자식요소에도 적용이 돼서, :hover한것과 다름이 없다

여기서 가장 짜증났던? 구현하면서 고민많이했던부분은 코드상에서 '이부분에 골치아팠음' 부분이다

분명 똑같이 설정을 했는데 닫을 때는 휙하고 사라져버려서 이유가 뭘까 고민하다가 

위가 setTimeout이기 때문에 setTimeout이 실행전에 ul이 아예 안보이기 때문에 발생하는 일이라는걸 알게되었다.

그래서 setTimeout시간을 조정해서 제어하니 내가 생각했던 그림이 나왔다.

 

그리고 hover했을 때 줄 그어지는 효과

css코드

.practice__wrapper .prac .dropdown__list .prac__list li {
  width: 250px;
  height: 0;
  opacity: 0;
  transition: all ease-out 0.3s;
  cursor: pointer;
  position: relative;
  color: black;
}
.practice__wrapper .prac .dropdown__list .prac__list li::after {
  position: absolute;
  content: '';
  top: 10px;
  left: 15px;
  width: 0px;
  height: 20px;
  border-color: transparent rgba(135, 135, 135, 0.2);
  border-style: solid dotted;
  background-color: rgba(255, 240, 73, 0.8);
  transform: skew(2deg, 2deg);
  transition: width ease-out 0.5s;
  opacity: 0;
  z-index: -1;
}
.practice__wrapper .prac .dropdown__list .prac__list li:hover {
  color: white;
}
.practice__wrapper .prac .dropdown__list .prac__list li:hover::after {
  width: 90%;
  opacity: 1;
}

li:hover::after 이런거 처음써봤다. 해보니까 돼서 더 신기했다.