如何在单击时切换选中/未选中状态时更改复选框标签的颜色 [英] How to change color of checkbox label while toggling checked/unchecked state on click

查看:1203
本文介绍了如何在单击时切换选中/未选中状态时更改复选框标签的颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我选中或取消选中时,我想更改复选框标签的字体颜色和背景颜色。我在这个网站上发现了一个javascript解决方案,但是没能使代码工作。这是我到目前为止所尝试的。现在它将highlight类附加到父div,我只想要更改标签。感谢您的时间。

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;
}


推荐答案

,您的代码似乎适用于包装复选框的标签,如下所示:

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>

更改html或更改JS以定位下一个元素,而不是最接近的父元素:

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 );
});

此外,您的CSS有问题,并且直接定位标签会占用突出显示类,

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.

这是一个小东西,我已经修正它是更具体的当瞄准highligth类:

Here's a fiddle, I've fixed it by being more specific when targeting the highligth class:

FIDDLE

并且Raminson是正确的,你应该用方括号和type =来定位复选框。

And Raminson is correct, you should target the checkbox with brackets and type="".

这篇关于如何在单击时切换选中/未选中状态时更改复选框标签的颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆