我想知道是否可以制作一个行为与单选按钮完全一样的 div?我试图在不使用很多人建议的 jquery 的情况下实现这一目标,我检查了网络并找到了一些。
我以前的做法是使用 javascript,这对少数人有效
function Switcher(a,b,c,d,e){
document.getElementById('button1').style.background=a;
document.getElementById('button2').style.background=b;
document.getElementById('button3').style.background=c;
document.getElementById('button4').style.background=d;
document.getElementById('button5').style.background=e;
}
点击事件
onClick="Switcher(#c5e043,#241009,#241009,#241009,#241009)"
然后每个单击的按钮都会切换,我可以添加检查单选按钮功能,但我注意到我可能需要增加到 20 个,这使得列表变得很长。
想知道是否有人有更简单的解决方案来解决这个问题?基本上我需要一个 div,它的行为就像一个单选按钮,在选择时改变 bgcolor 或 smthg(单选)
最佳答案
据我了解,您确实希望使用 div 而不是单选按钮来更好地控制外观。 如果可以的话,我的建议是使用真正的单选按钮:
使用真正的单选按钮后跟这样的标签:
<input type="radio" name="rGroup" value="1" id="r1" checked="checked" />
<label class="radio" for="r1"></label>
使用 CSS,隐藏单选按钮:
.radios input[type=radio] {
display:none
}
这样,您就可以根据需要设置标签的样式。我创建了一个简单的代码片段(和一个 jsfiddle),它充分演示了如何使用具有自定义外观的单选按钮。例如,我使用了一个小的彩色框,当它被选中时会发生变化。
.radios .radio {
background-color: #c5e043;
display: inline-block;
width: 10px;
height: 10px;
cursor: pointer;
}
.radios input[type=radio] {
display: none;
}
.radios input[type=radio]:checked + .radio {
background-color: #241009;
}
<div class="radios">
<input type="radio" name="rGroup" value="1" id="r1" checked="checked" />
<label class="radio" for="r1"></label>
<input type="radio" name="rGroup" value="2" id="r2" />
<label class="radio" for="r2"></label>
<input type="radio" name="rGroup" value="3" id="r3" />
<label class="radio" for="r3"></label>
</div>
Here是 jsfiddle
关于javascript - 制作一个像单选按钮一样的div,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18879084/