使用css3 制作switch开关

 使用css3来实现switch开关的效果:

html代码:

<!--switch开关-->
<div class="switch-btn">
  <input type='checkbox' id='switchs' checked class='switch-checkbox'>
  <label for='switchs' class='switch-left'></label>
  <label for='switchs' class='switch-right'></label>
</div>

label标签for属性的作用:将for属性值与input 中id值相等的标签关联起来,当点击label标签时,如radio,checkbox会随之选中或者不选中

 

css代码:

.switch-btn{
  position: relative;
}
.switch-btn .switch-checkbox{
  display:none;
}
.switch-btn .switch-left{
  display: block;
  width: 1.5rem;
  height: 1.5rem;
  left: 1.5rem;
  top: 0;
  border-radius: 50%;
  position: absolute;
  transition: 0.4s;
  background: #fff;
  z-index: 1;
  box-shadow: 1px 1px 2px #ccc;
}
.switch-btn .switch-checkbox:checked + .switch-left{
  left:0px;
  box-shadow:-1px 1px 2px #ccc;
}

.switch-btn .switch-right{
  display: block;
  width: 3rem;
  top: 0;
  height: 1.5rem;
  border-radius: 1rem;
  transition: 0.4s;
  background: #999;
  position: absolute;
}
.switch-btn .switch-checkbox:checked + .switch-left + .switch-right{
  background: #04BE02;
  transition:0.4s;
}

transform(变形,转换)http://www.w3school.com.cn/cssref/pr_transform.asp

transform的属性包括:rotate() / skew() / scale() / translate(,) ,分别还有x、y之分,比如:rotatex() 和 rotatey() ,translateX和translateY以此类推。

transition(过渡)http://www.w3school.com.cn/css3/css3_transition.asp

transition的属性值包括:transition-property(过渡属性名 all 必填),transition-duration(过渡周期时间 0.3s  必填),transition-timing-function(过渡方式 ease 必填),transition-delay(延迟时间 选填)

说明:.switch-checkbox:checked + .switch-left  (.switch-checkbox 被选中的时候后面的兄弟元素 设置.switch-left样式)

http://www.w3school.com.cn/cssref/selector_gen_sibling.asp

<script>

//使用onchange事件,获取当前是否是checked

var checkSwitch= document.getElementById('switchs');
checkSwitch.οnchange=function(event){
  console.log(event.target.checked);
}

</script>

 

转载于:https://www.cnblogs.com/leijee/p/7027056.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值