css - 重写checkbox样式 用到id 与label关联实现 但是现在checkbox循环生成多项 就不能用id了 求解决办法
PHP中文网
PHP中文网 2017-04-17 15:25:52
0
2
831
<p class="checkbox">
        <input id="awesome" type="checkbox">
        <label for="awesome"></label>
    </p>
    
     <style>
        .checkbox input[type="checkbox"]+label::before {
            content: '\a0';
            display: inline-block;
            margin-right: 0em;
            border-radius: 1em;
            width: 1.3em;
            height: 1.3em;
            line-height: 1.1em;
            background: silver;
            text-indent: .2em;
            vertical-align: 0.2em;
            font-size: 20px;
        }
        
        .checkbox input[type="checkbox"]:checked+label::before {
            background: yellowgreen;
            content: '\2605';
        }
        
        input[type="checkbox"] {
            position: absolute;
            display: none;
        }
    </style>

现在页面中有多个checkbox循环生成 就不能用id于label产生关联了
请问怎么解决

PHP中文网
PHP中文网

认证0级讲师

reply all(2)
Ty80

You can use js to generate dynamic id. Generate id = "awesome"+i for each input in the loop, and set the label's for attribute value to the same value.
Here is a simple example:

var body=document.getElementsByTagName('body')[0];
        for(var i=0;i<3;i++){
            var input=document.createElement("input");
            input.id="input"+i;
            var label=document.createElement("label");
            label.setAttribute("for","input"+i);
            label.innerHTML="点击";
            body.appendChild(label)
            body.appendChild(input)
        }
迷茫
<label class="label-checkbox">
<input type="radio" name="my-radio" checked="checked">
</label>

Wouldn’t it be better to write it this way? It’s so simple

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template