티스토리 뷰

Client

[Javascript] Spinner 구현하기

니용 2023. 4. 28. 08:05
반응형

 

이번 글에서는 Spinner라고 하여 Button에 애니메이션을 넣고 돌아가는 버튼을 구현해보려 합니다. 

 

샘플 코드 

샘플 코드는 Codepen이라는 것으로 보여지도록 처리하였습니다. 

See the Pen Untitled by Jay Park (@jyp90) on CodePen.

 

HTML

버튼은 심플하게 일반 버튼 내에 span 태그가 있는 것으로 설정하였습니다. 

<button type="button" class="button" onclick="this.classList.toggle('loading')">
    <span class="btn_text">Save</span>
</button>

 

CSS

기본적인 스타일과 버튼의 이미지를 부여합니다.

body {
  font-family: system-ui;
  background: #f06d06;
  color: white;
  text-align: center;
}

.button {
  position: relative;
  padding: 8px 16px;
  background: skyblue;
  border: 5px;
  outline: none;
  border-radius: 2px;
  cursor: pointer;
}

.button:active {
  background: #007a63;
}

.btn_text {
  font: bold 20px "Quicksand", san-serif;
  color: #ffffff;
  transition: all 0.2s;
}

.loading .btn_text {
  visibility: hidden;
  opacity: 0;
}

.loading::after {
  content: "";
  position: absolute;
  width: 16px;
  height: 16px;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  border: 4px solid transparent;
  border-top-color: #ffffff;
  border-radius: 50%;
  animation: loading-spinner 1s ease infinite;
}

 

그리고 모션을 위해 애니메이션을 추가합니다. 

@keyframes loading-spinner {
  from {
    transform: rotate(0turn);
  }

  to {
    transform: rotate(1turn);
  }
}

 

JavaScript

마지막으로 버튼이 작동하게 하기 위한 자바스크립트를 추가합니다. 

document.querySelector(".button").addEventListener("click", () => {
    theButton.classList.add("loading");
});

 

반응형
댓글
공지사항