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来实现这个功能的——点击的时候替换成另一个图片。结果问了下我们公司的前端,这么一搞,感觉好高大上啊!

路漫漫其修远兮,吾将上下而求索。

posted @ 2018-03-09 20:17  JMCui  阅读(9367)  评论(1编辑  收藏  举报