更改复选框标签css属性与复选框选中 [英] Change checkbox label css property with checkbox checked
问题描述
我有以下html:
<label>
<input type="checkbox" value="cb_val" name="cb_name">
my checkbox text
</label>
使用CSS我添加了一个背景颜色到< label& / code>标签。
With CSS I added a background-color to the <label>
tag.
label { background-color:#333; color:#FFF; }
现在我想在复选框被选中时更改标签的背景颜色。
我知道如何使用javascript,但是有一个方法到它只是使用CSS?
Now I'd liked to change the background color of the label when the checkbox is checked. I know how to do it with javascript, but is there a way to to it just using CSS?
我看到一些解决方案,但他们使用
I have seen some solutions, but they use the adjacent sibling selector and only work when the label appears after the checkbox.
我仍然希望在没有javascript的情况下解决这个问题,是否有任何人有线索?
I still hope to fix this without javascript, does anyone have a clue?
UPDATE:
我害怕,不能这样做,所以我必须做它与JS,或使用不同的HTML结构实现相同的视觉效果。
我想一次设置标签和文本框的背景颜色,所以我可以去一个解决方案,其中的复选框是绝对的标签顶部。好点PointTheldea!
As I was afraid of, it cannot be done this way, so i must do it with JS, or achieve the same visual effect with a different HTML structure. I want to set the background color of the label and the textbox in one go, so I can go with a solution where the checkbox is placed absolute on top of the label. Good point PlantTheldea!
或者我可以应用背景颜色到标签和复选框。
Or I can apply the background color to the label and the checkbox both.
推荐答案
您可以使用纯CSS实现这一点,
You can achieve this with pure css like so,
<input type="checkbox" id="cb_1" value="cb_val" name="cb_name">
<label for="cb_1">
my checkbox text
</label>
使用此css,
label { background-color:#333; color:#FFF; }
input[type="checkbox"]:checked + label {
background: brown;
}
请注意
这里是一个选项,它的样式更多的具有相同的外观如您所愿,新的小提琴。这不涉及任何绝对的定位,只是一些骗局。
Here is an option of styling it more to have the same appearance as you wanted, New fiddle. THIS DOES NOT involve positioning anything absolute, just some trickery.
这篇关于更改复选框标签css属性与复选框选中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!