html - 如何在没有js的情况下使用html和CSS更改标签颜色?

标签 html css

我正在使用复选框类型编码,我想针对特定选项进行设置,点击它后它会变成蓝色,而对于其他选项,我可以点击它然后它会变成红色或绿色。我已经找到一种方法来执行此操作,如 CSS 中所示,但我认为我必须继续为每种类型的标签编写代码。所以我想知道是否有更有效的方法来做到这一点?谢谢。这是代码:

input[type="checkbox"] {
	display: none;
}

label {
	cursor: pointer;
	color: #555;
	display: block;
	padding: 10px;
	margin: 3px;
}

input[type="checkbox"]:checked + label {
	color: #ffffff;
	font-weight: bold;
    background: blue;
}

input[type="checkbox"]:checked + label[for=red1] {
	color: #ffffff;
	font-weight: bold;
    background: red;
}

input[type="checkbox"]:checked + label[for=red2] {
	color: #ffffff;
	font-weight: bold;
    background: red;
}

input[type="checkbox"]:checked + label[for=green1] {
	color: #ffffff;
	font-weight: bold;
    background: green;
}
<div><input id="blue1" type="checkbox" /><label for="blue1">1 blue</label></div>
<div><input id="blue2" type="checkbox" /><label for="blue2">2 blue</label></div>
<div><input id="blue3" type="checkbox" /><label for="blue3">3 blue</label></div>
<div><input id="blue4" type="checkbox" /><label for="blue4">4 blue</label></div>
<div><input id="red1" type="checkbox" /><label for="red1">1 red</label></div>
<div><input id="red2" type="checkbox" /><label for="red2">2 red</label></div>
<div><input id="green1" type="checkbox" /><label for="green1">1 green</label></div>

最佳答案

您可以使用 CSS 'starts with' attribute selector (^=) 以选择具有以“red”、“green”等开头的 for 属性的所有标签

input[type="checkbox"] {
    display: none;
}

label {
    cursor: pointer;
    color: #555;
    display: block;
    padding: 10px;
    margin: 3px;
}

input[type="checkbox"]:checked + label {
    color: #ffffff;
    font-weight: bold;
    background: blue;
}

input[type="checkbox"]:checked + label[for^=red] {
    color: #ffffff;
    font-weight: bold;
    background: red;
}

input[type="checkbox"]:checked + label[for^=green] {
    color: #ffffff;
    font-weight: bold;
    background: green;
}

关于html - 如何在没有js的情况下使用html和CSS更改标签颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33511556/

相关文章:

html - ion-navbar 背景图像未出现 - 仅显示白色 - Ionic 3

javascript - 如何在用户单击按钮时使用 js 更改 css 类中的显示属性

html - 列表列不会将边框向下推?

jquery - 在 JQuery 中检查复选框

html - 使用 "display:table/table-cell"时出现神秘空白

javascript - 语义用户界面 : Collapsable sidebar with responsive content

html - Kendo ui mobile 将默认主题设置为 flat ui

html - 使用CSS绘制导航箭头形状

google-chrome - css3边框半径不适用于子元素

css - 完整的 CSS 属性表