首页 > 解决方案 > css/sass 中样式切换开关的问题

问题描述

我遇到了一些问题,我似乎无法根据需要设置拨动开关的样式。我目前有这样的:

在此处输入图像描述

在此处输入图像描述

然而,它需要看起来像这样:

在此处输入图像描述

在此处输入图像描述

这是我的 HTML:

   <label class="switch"><input #handlingUnitAdvancedOptionsCheckBox id="handlingUnitAdvancedOptionsCheckBox" type="checkbox" [checked]="handlingModel.advancedOptions" 
      (change)="handlingUnitAdvancedOptionsToggle(handlingUnitAdvancedOptionsCheckBox.checked)" />
      <span class="slider round"></span>
      </label>

这是我的CSS:

/* The switch - the box around the slider */
.switch {
  position: relative;
  display: inline-block;
  width: 50px!important;
  height: 24px!important;
  cursor: pointer;
 }

/* Hide default HTML checkbox */
.switch input {
 opacity: 0;
 width: 0;
 height: 0;
}

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

.slider:before {
  display: block;
  width: 22px!important;
  height: 22px!important;
  margin: 1px;
  background: #fff;
  position: absolute;
  top: 0;
  bottom: 0;
  right: 26px;
  border-radius: 20px;
  transition: margin .3s ease-in 0s;
  transition-property: margin;
  transition-duration: 0.3s;
  transition-timing-function: ease-in;
  transition-delay: 0s;
  box-shadow: 1px 2px 7px #444;
}

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

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

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

/* Rounded sliders */
.slider.round {
border-radius: 20px;
}

.slider.round:before {
border-radius: 50%;
}

不知道我在哪里出错或我需要调整什么。我曾尝试更改变换和填充,但似乎无法正确处理。

标签: csssass

解决方案


您可以使用以下解决方案:

.switch {
  cursor: pointer;
  display: inline-block;
  height: 24px;
  position: relative;
  width: 50px;
  overflow:hidden;
}

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

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

.slider:before {
  background: #fff;
  border-radius: 50%;
  bottom: 1px;
  box-shadow: 3px 0px 7px #444;
  content: "";
  display: block;
  height: 22px;
  left: 1px;
  position: absolute;
  right: 50px;
  top: 1px;
  width: 22px;
  transition-property: all;
  transition-duration: .6s;
}

input:checked + .slider {
  background: #236093;
}

input:checked + .slider:before {
  box-shadow: -3px 0px 7px #002551;
  left: calc(100% - 23px); /** width of .slider:before + 1px */
}

.slider.round {
  border-radius: 24px;
}
<label class="switch">
  <input #handlingUnitAdvancedOptionsCheckBox id="handlingUnitAdvancedOptionsCheckBox" type="checkbox" [checked]="handlingModel.advancedOptions" 
      (change)="handlingUnitAdvancedOptionsToggle(handlingUnitAdvancedOptionsCheckBox.checked)" />
  <span class="slider round"></span>
</label>


推荐阅读