css3实现切换按钮效果

一、需求分析

在移动端,经常会需要一个切换按钮,如图:

切换前

切换后

那我可以用css属性来实现这个按钮的切换功能

二、代码如下

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8">
        <style>
            #toggle{
                display: none;
            }
            #toggle+label{
                display: block;
                position: relative;
                width: 120px;
                height: 60px;
                padding: 2px;
                cursor: pointer;
                /* background-color: #ddd; */
                border-radius: 60px;

            }
            #toggle+label::before,#toggle+label::after{
                display: block;
                position: absolute;
                left: 1px;
                top: 1px;
                bottom: 1px;
            }
            #toggle+label::before{
                right: 1px;
                /* width: 122px;
                height: 60px; */
                border-radius: 60px;
                background-color: #f5f5f5;
                content: "";
                transition: background-color 0.4s;
            }
            #toggle+label::after{
                width: 58px;
                
                border-radius: 100%;
                background-color: #fff;
                content: "";
                transition: margin 0.4s;
                box-shadow: 1px 0px 5px 1px #ddd inset;
            }
            #toggle:checked + label::before{
                background-color: green;
            }
            #toggle:checked + label::after{
                margin-left: 62px;
            }
            .test{
                width: 100px;
                height: 100px;
                position: relative;
            }
            .box{
                position: absolute;
                display: block;
                
                left: 1px;
                top: 1px;
                bottom: 1px;
                right: 1px;
                background-color: pink;
            }
        </style>
    </head>
    <body>
    <div>
        <input type="checkbox" id="toggle">
        <label for="toggle"></label>
    </div>
    <div class="test">
        <div class="box"></div>
    </div>
    </body>
</html>

本案例中,以label::before作为切换按钮的卡槽,label::after作为按钮的小圆球。

利用css选择器:checked进行切换,改变切换前后label::before,和label::after的样式,即可实现切换效果。

备注:在设计before,和after伪元素的尺寸时,作为子元素,而且设置了position:absolute属性,当设置了left,top,right,bottom属性后,子元素的宽、高就确定了。

 

转载于:https://www.cnblogs.com/justinwxt/p/7083919.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值