barcode

슬라이드 버튼 만들기

Coding/JavaScript

사실 JS까지는 필요 없는데 본격적으로 굴려먹으려면 JS가 필요하니까 그냥 넘어가자.

 


Reference

https://www.w3schools.com/howto/howto_css_switch.asp\

 

How To Create a Toggle Switch

W3Schools offers free online tutorials, references and exercises in all the major languages of the web. Covering popular subjects like HTML, CSS, JavaScript, Python, SQL, Java, and many, many more.

www.w3schools.com


슬라이드버튼이 뭘 말하는거냐면

저 오른쪽 저 버튼을 말한다. 체크박스가 원류이긴 한데 얘는 체크박스와 달리 뭘 토글(껐다켰다)할 때 쓴다. 가장 많이 보는 케이스는 화면 설정에서 라이트모드-다크모드 전환할 때. 물론 기기 설정 따라가는것까지 선택지가 세개면 라디오버튼을 쓰지만.

 

<html>
  <body>
    <label for="toggle-slide" class="toggle-switch">
      <input type="checkbox" id="toggle-slide">
      <span class="toggle"></span>
    </label>
  </body>
</html>

HTML 코드는 간단하다. 그니까 뼈대는 간단한데 이제 살 붙일 때 노가다가 들어간다.

 

label {
  position: relative;
  display: inline-block;
  width: 150px;
  height: 25px;
}

#toggle-slide {
  display: none;
}

그 우리가 슬라이드 버튼을 누르면 쇽쇽 왔다갔다 하는 건 라벨을 지지고 볶아서 만든다. 즉, 체크박스는 필요가 없기 때문에 숨겨야 한다.

 

.toggle {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
}

.toggle:before {
  position: absolute;
  content: '';
  width: 23px;
  height: 23px;
  left: 5px;
  bottom: 5px;
  background-color: #fff;
  transition: .4s;
}

input:checked + .toggle {
  background-color: #00498c;
}

input:focus + .toggle {
  box-shadow: 0 0 1px #00498c;
}

input:checked + .toggle:before {
  transform: translateX(26px);
}

이렇게 하면 네모네모 멈뭄미의 저주를 받은 네모네모 슬라이드 버튼이 완성된다. 슬라이드 버튼은 라벨과 가상 선택자의 콜라보레이션을 통해 만들어진다. 속성 중 transition은 없으면 뭔가 약간... 그 어떤 느낌이냐면 뭔가 움직임이 어색해진다. 스무스한 움직임을 위해 꼭 transition을 넣어주자.

 

.toggle {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #ccc;
  transition: .4s;
  border-radius: 34px;
}

.toggle:before {
  position: absolute;
  content: '';
  width: 23px;
  height: 23px;
  left: 5px;
  bottom: 5px;
  background-color: #fff;
  transition: .4s;
  border-radius: 50%;
}

저는 마인크래프트스러운 버튼 싫은데요! 둥근거 좋아하는데요! 그러면 span이랑 span 가상 선택자에 border-radius를 주자. 여기서는 .toggle이 span, .toggle:before이 가상 선택자인데 가상 선택자가 누르면 쇽쇽 움직이는거고 span은 바깥에 그거다.

 

왜 라디오버튼이 아니라 체크박스로 하는지는 간단하다. 토글이라는건 화면을 새로고침 하지 않더라도 계속 선택해서 온오프를 해야 하는건데, 체크박스와 달리 라디오버튼은 토글이 안된다.