css3打造一个switch开关

团队开发项目时,需要用到一个switch开关,原先用的是mui-switch;可是mui-switch在IE下的表现很不好;
mui-switch在IE下的表现
于是,自己就动手写一个兼容IE的switch开关;
样式和mui-switch差不多,是长这样的(IE下的表现)
这里写图片描述
先附上源码:

.iSwitch{
  position: relative;
  display: inline-block;
  width: 60px;
  height: 30px;
  border-radius: 15px;
  background: #dcdcdc;
  border:1px solid #dcdcdc;
  box-shadow: 0 0 5px #dcdcdc;
  overflow: hidden;
  vertical-align: middle;

}
.iSwitch input{
  visibility: hidden;
}
.iSwitch i{
  position: absolute;
  top: 0;
  left: 0;
  display: inline-block;
  width: 50%;
  height: 100%;
  border-radius: 100%;
  background: #fff;
}
.iSwitch i::before{
  content: " ";
  display: none;
  width: 200%;
  height: 100%;
  border-radius: 25%;
  background: #61cafd;
}
.iSwitch i::after{
  content: " ";
  position: absolute;
  left: 0;
  top: 0;
  z-index: 2;
  display: inline-block;
  width: 100%;
  height: 100%;
  border-radius: 100%;
  background: #fff;
}
.iSwitch input:checked + i{
  transform:translateX(100%);
  -webkit-transform:translateX(100%);
}
.iSwitch input:checked + i:before{
  display: inline-block;
  transform:translateX(-50%);
  -webkit-transform:translateX(-50%);
}

原理就是使用:checked选择器实现开关的动态效果(开关打开时应用:checked的样式,关闭时应用正常的样式),而按钮的动画就是使用了css3的transform来实现的;

使用方式:

<label class="iSwitch">
    <input type="checkbox">
    <i></i>
</label> 
  • 如果要控制开关大小
    .iSwitch{
    width: 你的宽度;
    height: 宽度的一半;
    border-radius: 你的圆角大小;
    }
  • 如果要控制开关背景色
  .iSwitch i::before{
    background-color:你喜欢的颜色;
    }

为什么要多使用一个空标签<i>呢?
因为IE并不支持<input>的伪元素,所以使用去<input>的伪元素模拟按钮,并没有什么用,所以就用一个<i>去模拟。
为什么使用:before&:after
我把<input>隐藏起来,使用<i>:after来模拟按钮,<i>:before来改变开关的背景色。为啥要使用<i>:after来模拟按钮?因为<i>:before在渲染的时候回覆盖<i>(并不能通过z-index改变覆盖顺序),所以只好使用<i>:after来模拟按钮(如果你能解决,请告诉我解决方法)。
兼容性

  • chrome

  • IE8+

  • 360 6.5+

  • FireFox

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值