css使用checkbox来打造switch开关按钮

这是基础篇,所以要讲得仔细点,首先,我们有时候会看到这么一个需求:


这是一个很常见的控件,所以很有必要去掌握他,而我们需要的就是用到最常用的input标签,

<input  type="checkbox">


因为他有“切换”功能,可是又有一个问题,我们怎么把那个带有√号的框框改造成一个带有圆圈的,高大上的方块呢?
显然不能在他上面动手脚,这时候就要想到另外一个常和input一起使用的label标签了,因为他有“for”属性,可以实现将焦点转移到input标签上,而且他本身就是一个“空白”,可以很容易改造成我们所需要的类型,然后,对于checkbox的选中状态,又是我们事件处理的好方法,所以checkbox是特佳的选择,思路讲完了,希望大家能整理成自己的代码:


<!DOCTYPE html>

<head>
    <meta charset="UTF-8">
    <title></title>
    <link rel="stylesheet" href="css/style_all.css" />
    <style>

    </style>
</head>

<body>
    <input type="checkbox" class="widget_switch_checkbox" id="widget_switch_checkbox">
    <label for="widget_switch_checkbox" class="widget_switch_label">
            <span class="widget_switch_circle"></span>
        </label>
    <script>
        document.querySelector("input.widget_switch_checkbox").addEventListener("click", function() {
            if(document.querySelector("input.widget_switch_checkbox").checked) {
                console.log(new Date().getTime());
                console.log("选中状态");
            }
        });
    </script>
</body>

</html>

css文件如下:


/*开关按钮:模板
 *
 * 注意:此处尺寸设置死的
 *
 *
 <div id="container">
        <input type="checkbox" class="widget_switch_checkbox" id="widget_switch_checkbox">
        <label for="widget_switch_checkbox" class="widget_switch_label">
            <span class="widget_switch_circle"></span>
        </label>
    </div>
 
  */

/*点击事件则是使用:
  *     document.querySelector("input.widget_switch_checkbox").addEventListener("click", function() {
            if(document.querySelector("input.widget_switch_checkbox").checked) {
                console.log(new Date().getTime());
                console.log("选中状态");
            }
        });
  */

.widget_switch_checkbox {
    display: none;
}

.widget_switch_label {
    margin-top: 5px;
    background-color: grey;
    display: inline-block;
    position: relative;
    height: 30px;
    width: 80px;
    border-radius: 1000px;
    box-shadow: 0 0 2px black;
}

.widget_switch_checkbox:checked~.widget_switch_label .widget_switch_circle {
    left: 50px;
}

.widget_switch_circle {
    position: absolute;
    display: inline-block;
    height: 30px;
    width: 30px;
    border-radius: 50%;
    border: 2px solid #333;
    background-color: #eee;
    left: 0;
    /*过渡效果,可考虑不加*/
    -webkit-transition: all 0.3s;
    -moz-transition: all 0.3s;
    -ms-transition: all 0.3s;
    -o-transition: all 0.3s;
    transition: all 0.3s;
}

.widget_switch_checkbox:checked~.widget_switch_label {
    background: lime;
}

希望大家整理成自己的东西,不懂得属性建议百度,加油


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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值