更改聚焦时的标签背景颜色复选框

Change label background color on focusing Check box

本文关键字:背景 颜色 复选框 标签 聚焦      更新时间:2023-10-05

我有一个复选框,它位于标签控件内。我需要更改标签背景颜色上的焦点一个复选框。

我看到Textbox的源代码如下:

input:focus + label {background-color: red;}

我已经尝试了上面的复选框代码,但复选框不起作用。

input[type="checkbox"]:focus + label {background-color: red;}

请帮我处理这个

Fiddle演示

由于输入是标签的子级,因此没有CSS选择器可以影响/选择它。

然而,使用Jquery是一件简单的事情。

$(document).ready(function () {
    $('input').focus(function () {
        $(this).parents('label').addClass('focused');
    });
    $('input').blur(function () {
        $(this).parents('label').removeClass('focused');
    });
});
label {
    float:left;
}
.focused {
    outline:none;
    box-shadow: 0 0 1px 2px rgba(0, 240, 255, 0.4);
    background-color : rgba(0, 240, 255, 0.4);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label for="chkYesIsSubPropofferedSale">Check
    <input id="chkYesIsSubPropofferedSale" type="checkbox" />
</label>

注意:我的JQ技能是次要的,所以我相信这是可以改进的。

在Paulie_D给出的答案和Alexander提供的小提琴的基础上,我提出了以下小提琴

它使用jQuery悬停事件来从复选框的父标签中附加和删除类——希望这对您有一些用处。有问题的jQuery如下:

$('.checkBoxClass').hover(
  function()
  { 
     $(this).parent('label').addClass('focused');
  },
  function()
  { 
     $(this).parent('label').removeClass('focused');
  }  
);

聚焦的位置先前已定义为所需的背景色。然而,你不需要使用类,你可以单独设置颜色:

$(this).parent('label').css('background-color', 'red');

如果没有JavaScript,除非两个元素在DOM树中具有相同的父元素,否则无法做到这一点。element1 + element2是"后继"选择器,它将规则应用于紧接在element1之后的每个element2。但是使用CSS,您可以直观地将一个元素放置在另一个元素中,而不必将其作为父元素。POC:

label {
  float:left;
  margin-right: -22px;
  padding-right: 22px;
}
input:focus + label {background-color: red;}
input[type="checkbox"]:focus + label {
  outline:none;
  box-shadow: 0 0 1px 2px rgba(0, 240, 255, 0.4);
  background-color : rgba(0, 240, 255, 0.4);
}
<div class="row">
  <input id="contact_form_mail" name="contact_form_mail" type="email" placeholder="Your e-mail address...">
  <label><input id="chkYesIsSubPropofferedSale" type="checkbox"></label>
  <br>
  <input id="chkYesIsSubPropofferedSale" type="checkbox">
  <label>Check</label>
</div>