css重寫checkbox樣式

1、前言

默認的checkbox長這樣:css

        <p>
            <span><input type="checkbox" /></span>
            <span>空閒</span>
            <span><input type="checkbox" /></span>
            <span>服務中</span>
        </p>

有點醜,我想把它變成這樣:前端

2、實現

一、checkbox 難看的框框隱藏掉,改用<label>元素鏈接到checkbox

        <p>
            <input type="checkbox" class="e-selfecheckbox" id="place1">
            <label class="selfecheckbox_label" for="place1">空閒</label>

            <input type="checkbox" class="e-selfecheckbox" id="place2">
            <label class="selfecheckbox_label" for="place2">服務中</label>
        </p>
        <style>
            .e-selfecheckbox{
                display: none;
            }
        </style>

二、隱藏的框框的用自定義圖片來代替

        <style type="text/css">
            .e-selfecheckbox {
                display: none;
            }
            
            .selfecheckbox_label:before {
                content: "";
                display: inline-block;
                vertical-align: middle;
                width: 13px;
                height: 13px;
                background-image: url(img/scheduling_icon_uncheck2.png);
                background-size: 100%;
            }
        </style>

三、給checkbox註冊事件,原理就是點擊的時候把他替換成另外一張圖片

        <style type="text/css">
            .e-selfecheckbox {
                display: none;
            }
            
            .selfecheckbox_label:before {
                content: "";
                display: inline-block;
                vertical-align: middle;
                width: 13px;
                height: 13px;
                background-image: url(img/scheduling_icon_uncheck2.png);
                background-size: 100%;
            }
            
            /*在e-selfecheckbox元素被選擇的時候,將selfecheckbox_label前面的圖片替換成另外一張*/
            .e-selfecheckbox:checked+.selfecheckbox_label:before {
                background-image: url(img/scheduling_icon_checked2.png);
            }
        </style>

四、實現效果

3、結語

原本思路是想用js來實現這個功能的——點擊的時候替換成另外一個圖片。結果問了下咱們公司的前端,這麼一搞,感受好高大上啊!url

路漫漫其修遠兮,吾將上下而求索。spa

相關文章
相關標籤/搜索