改变颜色的标签和Div周围输入+标签点击

Change Color of Label and Div Around Input + Label on Click

本文关键字:标签 输入 周围 Div 变颜色 改变      更新时间:2023-09-26

提前感谢!Javascript新手。

我需要开发自定义复选框,坐在一个div内,当你点击标签或复选框的div的边界和字体颜色改变。本以为我可以用CSS做到这一点,但我开始认为我需要JS。

下面是目前为止的代码: CSS:

input[type=checkbox] {
    display: none;
}
div.label {
    display:block;
    border: 1px solid gray;
    border-radius: 23px;
    line-height: 30px;
    height:50px;
    width: 225px;
    text-align:center;
}
label {
    color:gray;
    line-height:50px;
}
label:before {
    content: "";
    display: inline-block;
    width: 13px;
    height: 13px;
    margin-right: 10px;
    background-color: #ffffff;
}

input[type=checkbox]:checked + label:before {
    content: "'2713";
    font-size: 15px;
    color: red;
    line-height: 15px;
    margin-left:10px; 
    margin-top: 15px;
}
input[type=checkbox]:checked + label:after {
    color: red;
}
HTML:

<div class="label">
<input id="weekly" type="checkbox" name="lists[weekly]" value="True" />
<label for="weekly">Weekly Preview Email</label><br>
</div>

任何帮助都是非常感激的!

使用jQuery

$(function(){
    $('input[type="checkbox"]').on('change', function(e){
        return $(this).parent().toggleClass('checked');
    });
});

这将为父div添加一个"checked"类。你可以为父div定义CSS。

在这里工作。

EDIT:根据注释,在CSS中添加一个样式来为标签上色。小提琴。

只需要CSS:

复选框需要直接位于您想要样式化的第一个内容之前。在你的例子中,它需要在div.label的前面。对于页面中的多个div,请确保更改每个for和相应的id

input:checked + div将只针对已检查过的输入后的div。

有一个jsBin示例!(现在带勾号)

下面是带有多个复选框和div

的相同示例HTML

<input id="weekly" type="checkbox" name="lists[weekly]" value="True" />
<div class="label">    
<label for="weekly">Weekly Preview Email (click me)</label><br>
</div>
CSS

input[type=checkbox] {
    display: none;
}
input:checked + div {
    border: solid 1px #000;
    color: #F00;
}
input:checked + div:before {
    content: "'2713";
    padding: 20px;
}

我会这样做

$('.label').click(function(){debugger;
$(this).toggleClass("checked")

});

添加一个checked css类

.checked {
   border:1px solid black;
   color:red;
}

它会做你想要的,改变边框/文本选中/取消选中复选框或点击标签。

这里的

小提琴