css重寫checkbox樣式


一、前言

默認的checkbox長這樣:

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

有點丑,我想把它變成這樣:

二、實現

1、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>

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

        <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>

3、給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>

4、實現效果

三、結語

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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM