开发者

Highlight label if checkbox is checked

开发者 https://www.devze.com 2023-02-16 02:17 出处:网络
Is there a non-javascript way of changing the color of a label when the corresponding checkbox is chec开发者_如何学编程ked?Use the adjacent sibling combinator:

Is there a non-javascript way of changing the color of a label when the corresponding checkbox is chec开发者_如何学编程ked?


Use the adjacent sibling combinator:

.check-with-label:checked + .label-for-check {
  font-weight: bold;
}
<div>
  <input type="checkbox" class="check-with-label" id="idinput" />
  <label class="label-for-check" for="idinput">My Label</label>
</div>


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

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

I like to rely on implicit association of the label and the input element, so I'd do something like this:

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

with CSS:

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

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


This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-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.

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


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

HTML

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

CSS

.highlight{
    background:yellow;
}

jQuery

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

This will work in all browsers

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

0

精彩评论

暂无评论...
验证码 换一张
取 消