问题
I'm trying to change the font color and background color of my checkbox label when I check or uncheck. I found a javascript solution on this site but haven't been able to make the code to work. Here is what I've tried so far. Right now it is attaching the "highlight" class to the parent div and I only want the label to change. Thanks for your time.
HTML:
<div class="checkboxes">
<input type="checkbox" name="1" id="option one" value="orange"><label for="1" class="highlight">Orange</label>
<input type="checkbox" name="2" id="option two" value="apple"><label for="1" class="highlight">Apple</label>
</div>
JavaScript:
$( '.checkboxes' ).on( 'click', 'input:checkbox', function () {
$( this ).parent().toggleClass( 'highlight', this.checked );
}); // end checkbox style
CSS:
.checkboxes label {
font-family:Open Sans Italic;
font-size: 12px;
color: #666;
border-radius: 20px 20px 20px 20px;
background: #f0f0f0;
padding: 3px 10px;
text-align: left;
}
.highlight {
font-family:Open Sans Italic;
font-size: 12px;
color: white;
border-radius: 20px 20px 20px 20px;
background: #86b3c1;
padding: 3px 10px;
text-align: left;
}
回答1:
The label comes after the checkbox, your code seems to be meant for a label that is wrapping the checkbox, like so:
<label for="1" class="highlight">Orange
<input type="checkbox" name="1" id="option one" value="orange">
</label>
Change the html or change the JS to target the next element and not the closest parent element:
$( '.checkboxes' ).on( 'click', 'input[type="checkbox"]', function () {
$( this ).next('label').toggleClass( 'highlight', this.checked );
});
Also, your CSS is faulty, and targeting the label directly will take presedence over the highlight class, so it will never change color even if the class is applied.
Here's a fiddle, I've fixed it by being more specific when targeting the highligth class:
FIDDLE
And Raminson is correct, you should target the checkbox with brackets and type="".
回答2:
You can do it using just CSS:
input[type=checkbox]:checked + label { /* styles that get changed */ }
demo http://dabblet.com/gist/3157721
Also, while producing the demo I've noticed a couple of issues:
id="option one"- the id must be only one and you cannot have spaces- the value of the
forattribute of thelabelshould be theid(notname) of the correspondinginput; this also lets you check/ uncheck the checkbox by clicking on the label and not on the checkbox itself
回答3:
closest() does not find a closest element to the selected element. it finds the closest parent, you can use next() method, try the following:
Get the first element that matches the selector, beginning at the current element and progressing up through the DOM tree.
$('.checkboxes').on('click', 'input[type="checkbox"]', function () {
$(this).next('label').toggleClass('highlight', this.checked);
});
please note that :checkbox selector is deprecated.
来源:https://stackoverflow.com/questions/11596837/how-to-change-color-of-checkbox-label-while-toggling-checked-unchecked-state-on