본문 바로가기
UX 개발/CSS

display: none에 애니메이션 추가하기

반응형

display: none을 활용한 element의 숨김/표시는 가장 기본적인 방식의 show/hide 처리방법입니다. 다만 CSS transition이 적용되지 않기 때문에 자연스러운 애니메이션을 구현하기 위해서는 약간의 추가적인 작업을 필요로 합니다.

 

간단한 클래스 추가 과정을 통해서 display: none을 활용한 show/hide 처리에 애니메이션을 추가하는 방법을 알아보고자 합니다.

기본적으로 animation을 display 개체에 추가해서 애니메이션을 추가함과 함께 display: none 속성을 애니메이션 재생 이후에 딜레이를 주어 추가함으로써 자연스러운 트랜지션이 가능하게 하는 방식입니다. 

  • [2022-02/2022-06 내용 추가] 본 내용은 display: none에 애니메이션을 추가하는 기본적인 방법만을 소개한 것이니 이 부분 참고 바랍니다. setTimeout을 함께 사용한 이유는 클릭 후 딜레이가 생기는 부분을 처리하기 위해 임시로 삽입한 부분입니다. 콜백함수를 통해 함수실행 순서를 조절하거나, debounce 등의 UI 관리 테크닉을 통해 보다 고도화된 구현이 가능할 것이오니, 관련 내용에 대해 추가적인 내용 파악이 필요하신 분은 추가 리서치를 진행하시기를 권장 드립니다.

HTML

<div class="container">
  <div class="trigger test-button">클릭하면 display: none을 block으로 변경합니다. </div>
  <div class="hidden test-button">I'm hidden</div>
</div>

CSS

.hidden {
  display: none;
  opacity: 0;
}

.appear {
  animation: fade-in 1s;
  animation-fill-mode: forwards;
  display: flex;
}

.disappear {
  animation: fade-out 1s;
  animation-fill-mode: forwards;
}

@keyframes fade-in {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes fade-out {
  from {
    opacity: 1;

  }
  to {
    opacity: 0;
  }
}

.container {
  font-family: sans-serif;
}


.test-button {
  border: 1px solid #ddd;
  padding: 1rem;
  background: #f5f5f5;
  cursor: pointer;
  text-align: center;
  margin: 1rem;
}

.test-button:hover {
  background: #eee;
}

JS

document.querySelector('.trigger').addEventListener('click', function(){
  document.querySelector('.hidden').classList.remove('disappear');
	document.querySelector('.hidden').classList.add('appear');
});

document.querySelector('.hidden').addEventListener('click', function() {
  const target = this;
  if (target.classList.contains('appear')) {
    target.classList.add('disappear');
    setTimeout(function(){ target.classList.remove('appear')},1001);
  }
});

참고자료

https://stackoverflow.com/questions/3331353/transitions-on-the-css-display-property

반응형
외주/과외 문의