It's our wits that make us men.

swtich小开关

Posted on By Wei Bin

CSS

       * {
        margin: 0;
        padding: 0
     }
    
    .switch {
        width: 50px;
        margin-top: 3px;
        height: 22px;
        background: #4f7cfe;
        cursor: pointer;
        border-radius: 11px;
        position: relative;
        transition: all .1s linear;
    }
    
    .switch em {
        position: absolute;
        left: 5px;
        top: 0;
        line-height: 22px;
        width: 25px;
        color: #fff;
        font-style: normal;
        font-size: 12px;
        transition: all .1s linear;
    }
    
    .switch i {
        position: absolute;
        left: 29px;
        top: 1px;
        background: #fff;
        width: 20px;
        height: 20px;
        display: block;
        border-radius: 10px;
        transition: all .1s linear;
    }
    
    .switch.switchOn {
        background: #ccc;
    }
    
    .switch.switchOn em {
        left: 23px;
    }
    
    .switch.switchOn i {
        left: 1px;
    }

JS

   <div class="switch"><em>ON</em><i></i></div>
    <script>
    $(".switch").click(function() {
        if ($(this).hasClass("switchOn")) {
            $(this).removeClass("switchOn");
            $(this).find("em").text("ON");
        } else {
            $(this).addClass("switchOn");
            $(this).find("em").text("OFF");

        }
    })
    </script>