0

Можете подсказать как сделать такой checkbox используя js? Стилизовать не обязательно, просто хочу понять как такое сделать.


введите сюда описание изображения

1

1 ответ 1

3

Тупо HTML и CSS

.flip {
  position: relative;
  display: inline-block;
  background-color: transparent;
  border: 2px solid pink;
  border-radius: 24px;
  padding: 4px;
}

input[type="checkbox"] {
  display: none;
}

span {
  position: relative;
  padding: 6px;
  display: inline-block;
  width: 82px;
  text-align: center;
  font-family: consolas;
  font-weight: 600;
}

.active:after {
  position: absolute;
  content: "";
  width: 100%;
  height: 100%;
  left: 0;
  top: 0;
  background-color: pink;
  border-radius: 24px;
  z-index: -1;
  transition: .5s;
}

input[type="checkbox"]:checked+label .active:after {
  left: 104%;
}
<div class="flip">
  <input type="checkbox" id="flip">
  <label for="flip">
    <span class="active">No</span>
    <span>Yes</span>
   </label>
</div>

Вот с JS

const checkox = document.querySelectorAll('.checkox');

for (let i = 0; i < checkox.length; i++) {
  checkox[i].addEventListener('click', function() {
    this.classList.toggle('active');
  })
}
.checkox {
  position: relative;
  width: 240px;
  height: 42px;
  border: 2px solid red;
  border-radius: 24px;
  margin: 6px 0;
}

.pereklyuchatel {
  position: absolute;
  width: calc(50% - 10px);
  height: calc(100% - 10px);
  top: 5px;
  left: 5px;
  background-color: red;
  border-radius: 24px;
  transition: .5s;
}

.active .pereklyuchatel,
.checkox.active:nth-child(2):after {
  left: calc(50% + 5px);
}

.checkox:nth-child(2):after {
  content: "";
  position: absolute;
  width: calc(50% - 10px);
  height: calc(100% - 10px);
  top: 5px;
  left: 5px;
  background-color: red;
  border-radius: 24px;
  transition: .5s;
}
<div class="checkox">
  <div class="pereklyuchatel"></div>
</div>

<div class="checkox"></div>

7
  • Видел это решение. Интересует решение именно через JS, если такое возможно.
    – rg234
    17 мар 2022 в 13:48
  • @rg234 поменял, можете посмотреть
    – Miha
    17 мар 2022 в 14:06
  • Спасибо большое, не думал что решение через JS настолько простое
    – rg234
    17 мар 2022 в 14:25
  • В варианте с JS чекбокс на сервер не улетит. Правда автор вопроса и не просил. 17 мар 2022 в 14:26
  • Laukhin Andrey, а возможно это как исправить? Или остается только html+css?
    – rg234
    17 мар 2022 в 14:27

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.