css - 重写checkbox样式 用到id 与label关联实现 但是现在checkbox循环生成多项 就不能用id了 求解决办法
本文介绍了css - 重写checkbox样式 用到id 与label关联实现 但是现在checkbox循环生成多项 就不能用id了 求解决办法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
问 题
<div class="checkbox">
<input id="awesome" type="checkbox">
<label for="awesome"></label>
</div>
<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产生关联了
请问怎么解决
解决方案
可以用 js 生成动态 id 吧。在循环中给每个 input 生成 id = "awesome"+i,同时把 label 的 for 属性值也设置成一样的。
下面是简单的示例:
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)
}
这篇关于css - 重写checkbox样式 用到id 与label关联实现 但是现在checkbox循环生成多项 就不能用id了 求解决办法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文