Html 如果选中复选框,则突出显示标签

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5275857/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 07:17:52  来源:igfitidea点击:

Highlight label if checkbox is checked

htmlcss

提问by Vladimir Keleshev

Is there a non-javascript way of changing the color of a label when the corresponding checkbox is checked?

当相应的复选框被选中时,是否有一种非 javascript 的方式来改变标签的颜色?

回答by Andrew Marshall

If you have

如果你有

<div>
  <input type="checkbox" class="check-with-label" id="idinput" />
  <label class="label-for-check" for="idinput">My Label</label>
</div>

you can do

你可以做

.check-with-label:checked + .label-for-check {
  font-weight: bold;
}

See this working. Note that this won't work in non-modern browsers.

看到这个工作。请注意,这在非现代浏览器中不起作用。

回答by Walter Rumsby

I like Andrew's suggestion, and in fact the CSS rule only needs to be:

我喜欢 Andrew 的建议,事实上 CSS 规则只需要:

:checked + label {
   font-weight: bold;
}

I like to rely on implicit association of the labeland the inputelement, so I'd do something like this:

我喜欢依赖于labelinput元素的隐式关联,所以我会做这样的事情:

<label>
   <input type="checkbox"/>
   <span>Bah</span>
</label>

with CSS:

使用 CSS:

:checked + span {
    font-weight: bold;
}

Example: http://jsfiddle.net/wrumsby/vyP7c/

示例:http: //jsfiddle.net/wrumsby/vyP7c/

回答by Teocci

This is an example of using the :checkedpseudo-class to make forms more accessible. The :checkedpseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

这是使用:checked伪类使表单更易于访问的示例。该:checked伪类可以隐藏输入及其可见的标签可以用来构建交互式窗口小部件,如图像画廊。我为想要测试的人创建了剪辑。

input[type=checkbox] + label {
  color: #ccc;
  font-style: italic;
} 
input[type=checkbox]:checked + label {
  color: #f00;
  font-style: normal;
} 
<input type="checkbox" id="cb_name" name="cb_name"> 
<label for="cb_name">CSS is Awesome</label> 

回答by Hussein

You can't do this with CSS alone. Using jQuery you can do

单独使用 CSS 无法做到这一点。使用 jQuery 你可以做到

HTML

HTML

<label id="lab">Checkbox</label>
<input id="check" type="checkbox" />

CSS

CSS

.highlight{
    background:yellow;
}

jQuery

jQuery

$('#check').click(function(){
    $('#lab').toggleClass('highlight')
})

This will work in all browsers

这将适用于所有浏览器

Check working example at http://jsfiddle.net/LgADZ/

http://jsfiddle.net/LgADZ/检查工作示例