如果取消选中,如何才能对此切换按钮进行转换?

时间:2017-07-21 07:34:41

标签: html css html5 css3

正如您在底部的jsfiddle中看到的那样,我做了一个简单的切换。检查开关时,它会执行“transform:scale”动画。 不幸的是,取消选中时它不会动画。 取消选中时如何强制它进行转换?

如果您想指出一种更好的方法来进行此类切换,请执行此操作。

.switch {
   display: inline-block;
   float: right;
   padding: 8px;

}

.switch input {
   display: none;
}

.switch label {
   cursor: pointer;
   width: 40px;
   height: 10px;
   background: #5B5B5B;
   display: inline-block;
   border-radius: 2px;
   position: relative;
   box-shadow: 0px 1px 2px 1px #333 inset;
   transition: all .2s ease;
}

.switch label:after {
   content: '';
   position: absolute;
   top: -4px;
   left: 0px;
   width: 16px;
   height: 16px;
   background: #d1d1d1;
   border-radius: 2px;
   transition: all .2s ease;
   box-shadow: 0px 1px 2px 1px #333;
}

.switch input:checked + label {
   background: #427db7;
}

.switch input:checked + label:after {
   transform: translate(24px, 0);
}

.switch label:active:after {
   transform: scale(1.2, 1.2);
}
<div class="switch">   
   No
   <input id="sw_1" type="checkbox" />
   <label for="sw_1"></label>
   Yes
</div>

1 个答案:

答案 0 :(得分:2)

试用此代码

使用css keyframes

.switch {
   display: inline-block;
   float: right;
   padding: 8px;

}

.switch input {
   display: none;
}

.switch label {
   cursor: pointer;
   width: 40px;
   height: 10px;
   background: #5B5B5B;
   display: inline-block;
   border-radius: 2px;
   position: relative;
   box-shadow: 0px 1px 2px 1px #333 inset;
   transition: all .2s ease;
   -webkit-transition:all .2s ease;
}

.switch label:after {
   content: '';
   position: absolute;
   top: -4px;
   left: 0px;
   width: 16px;
   height: 16px;
   background: #d1d1d1;
   border-radius: 2px;
   transition: all .2s ease;
   box-shadow: 0px 1px 2px 1px #333;
}

.switch input:checked + label {
   background: #427db7;
}
.switch input:checked + label:after {
   animation: FadeIn .2s ease;
   animation-fill-mode: both;
}
@keyframes FadeIn { 
  0% {
    transform: translate(0px, 0) scale(1.2, 1.2);
  }
  100% {
    transform: translate(24px, 0) scale(1, 1);
  }
}
.switch input + label:after {
   animation: FadeOut .2s ease;
   animation-fill-mode: both;
}

@keyframes FadeOut { 
  0% {
    transform: translate(24px, 0) scale(1.2, 1.2);
  }
  100% {
    transform: translate(0px, 0) scale(1, 1);
  }
}
<div class="switch">   
   No
   <input id="sw_1" type="checkbox" />
   <label for="sw_1"></label>
   Yes
</div>