单击任何单选按钮以切换开关

时间:2019-07-10 06:12:58

标签: html css

我想使整个单选按钮都可单击。 例如,当我单击第一个时,它将切换为“ OFF”,而当我再次单击时,它将切换回“ ON”,就像普通的切换开关一样。

只有当我单击该特定单选按钮时,它才会切换。你可以从我的小提琴中看到。

Fiddle

感谢您的帮助。谢谢!

.switch {
  background: white;
  border-radius: 3px;
}

.switch-label {
  position: relative;
  z-index: 2;
  float: left;
  width: 58px;
  line-height: 26px;
  font-size: 11px;
  color: rgba(255, 255, 255, 0.35);
  text-align: center;
  text-shadow: 0 1px 1px rgba(0, 0, 0, 0.45);
  cursor: pointer;
}
.switch-label:active {
  font-weight: bold;
}

.switch-label-No {
  padding-left: 2px;
}

.switch-label-Yes {
  padding-right: 2px;
}


.switch-input {
  display: none;
}
.switch-input:checked + .switch-label {
  font-weight: bold;
  color: rgba(0, 0, 0, 0.65);
}
.switch-input:checked + .switch-label-Yes ~ .switch-selection {
  left: 60px;
  background-color:red;
  /* Note: left: 50%; doesn't transition in WebKit */
}
.switch-selection {
  position: absolute;
  z-index: 1;
  left: 2px;
  display: block;
  width: 58px;
  height: 22px;
  border-radius: 3px;
  background-color: #65bd63;
  -webkit-box-shadow: inset 0 1px rgba(255, 255, 255, 0.5), 0 0 2px rgba(0, 0, 0, 0.2);
  box-shadow: inset 0 1px rgba(255, 255, 255, 0.5), 0 0 2px rgba(0, 0, 0, 0.2);
  -webkit-transition: left 0.15s ease-out;
  -moz-transition: left 0.15s ease-out;
  -ms-transition: left 0.15s ease-out;
  -o-transition: left 0.15s ease-out;
  transition: left 0.15s ease-out;
}
<div class="switch">
    <input type="radio" class="switch-input" name="view" value="1" id="week" checked>
    <label for="week" class="switch-label switch-label-No">ON</label>
    <input type="radio" class="switch-input" name="view" value="month" id="month">
    <label for="month" class="switch-label switch-label-Yes">OFF</label>
    <span class="switch-selection"></span>
</div>

1 个答案:

答案 0 :(得分:0)

希望这对您有帮助:

HTML:

  <label class="switch">
   <input type="checkbox">
   <span class="slider"></span>
  </label>

CSS:

.switch {
  position: relative;
  display: inline-block;
  width: 60px;
  height: 34px;
}

.switch input { 
  opacity: 0;
  width: 0;
  height: 0;
}

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

.slider:before {
  position: absolute;
  content: "";
  height: 26px;
  width: 26px;
  left: 4px;
  bottom: 4px;
  background-color: white;
  -webkit-transition: .4s;
  transition: .4s;
}

input:checked + .slider {
  background-color: #2196F3;
}

input:focus + .slider {
  box-shadow: 0 0 1px #2196F3;
}

input:checked + .slider:before {
  -webkit-transform: translateX(26px);
  -ms-transform: translateX(26px);
  transform: translateX(26px);
}