标签焦点不会更改css样式

Label focus does not change css style

本文关键字:css 样式 焦点 标签      更新时间:2023-09-26

我有一个简单的表单,想通过更改背景色来突出显示聚焦标签,但jquery在这里似乎不起作用。控制台没有显示任何错误。有人能帮我吗?

<form action="" method="POST" id="qrForm">
    <label for="enter1">Enter<input id='enter1' type="radio" name="enter"></label>
    <label for="enter2">Exit<input id='enter2' type="radio" name="enter"></label><br>
    <label for="device1">Took a device<input id="device1" type="radio" name="device"></label>
    <label for="device2">Returned a device<input id="device2" type="radio" name="device"></label>
</form>
<script>
    $("label").focus(function(){
        $(this).css('background-color', '#00CC66');
    });
</script>

实际上,我可以通过添加/删除一个类来完成它,但我想知道为什么这个不起作用。

既然可以在CSS中使用js,为什么还要使用它?

label:focus {
    background-color: #00cc66;
}

如果您希望label元素是可聚焦的,您也希望添加tabindex=0,但是,就像您单击标签一样,焦点会移动到相关的input元素

或者,您可以使用css下一个同级选择器,如下所示:

html:

<input type="text" id="foo" class="foo"><label for="foo">label</label>

和css:

.foo:focus + label {
    background-color: #00cc66;
}

或者使用不同的标记和css选择器

您不能使用.focus()来触发标签的焦点,而只能使用input来触发,请查看此处

$("input").focus(function(){
    $('label').css('background', '#00CC66');
});

$("input").focus(function(){
    $(this).closest('label').css('background', '#00CC66');
});

试试这个,因为你不能在标签上使用焦点-

$( "form input:radio" ).focus(function(){
            $(this).parent('label').css('background-color', '#00CC66');
        });