我有一个简单的表单,想通过更改背景颜色来突出显示聚焦的标签,但 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 的 next sibling 选择器,如下所示:
html:
<input type="text" id="foo" class="foo"><label for="foo">label</label>
和CSS:
.foo:focus + label {
background-color: #00cc66;
}
或者使用不同的标记和 CSS 选择器
关于javascript - 标签焦点不改变css样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38741601/