我设置了 input:focus + label
的样式,以直观地指示输入何时使用键盘导航获得焦点。
但是 Chrome(也许不仅仅是 Chrome?)在使用鼠标单击输入后会保持 :focus
状态,这看起来很难看。
我想在点击后删除 :focus
样式,不改变键盘导航。即,当您在单击标签后将鼠标移开时,它应该不再是红色的。
我看到了关于 .blur()
mouseup 上的输入的建议;但是 1) 它对我不起作用(请参阅下面的代码片段),并且 2) 我担心它会使键盘导航脱离其通常的流程。
是的,有人使用鼠标单击复选框然后转到键盘导航是一种边缘情况。但这是一个我想解释的问题。
$("label").mouseup(function () {
$(this).blur(); // This has no apparent affect.
$("#" + this.htmlFor).blur(); // Or this.
});
input:hover + label, input:focus + label {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Form Part One</p>
<input type="checkbox" id="cb1" name="cb" /><label for="cb1">First Checkbox</label><br>
<input type="checkbox" id="cb2" name="cb" /><label for="cb2">Second Checkbox</label>
<p>Form Part Two</p>
<input type="radio" id="r1" name="r" /><label for="r1">First Radio</label><br>
<input type="radio" id="r2" name="r" /><label for="r2">Second Radio</label>
</form>
最佳答案
EDITED 根据评论:
//set checkbox hover
$("input").hover(function() {
$(this).next("label").css("color", "red");
}, function() {
$(this).next("label").css("color", "black");
});
//set label hover
$("label").hover(function() {
$(this).css("color", "red");
}, function() {
$(this).css("color", "black");
});
//set checkbox focusin focusout
$("input").focusin(function() {
$(this).next("label").css("color", "red");
$(this).next("label").siblings().css("color", "black");
});
//set checkbox label active on click
$('input:checkbox').on('click', function() {
$(this).next('label').toggleClass('active');
});
//set radio label active on click
$('input:radio').on('click', function() {
$(this).next('label').toggleClass('active');
$(this).siblings().next('label').removeClass('active');
});
.active {
color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<p>Form Part One</p>
<input type="checkbox" id="cb1" name="cb" /><label for="cb1">First Checkbox</label><br>
<input type="checkbox" id="cb2" name="cb" /><label for="cb2">Second Checkbox</label>
<p>Form Part Two</p>
<input type="radio" id="r1" name="r" /><label for="r1">First Radio</label><br>
<input type="radio" id="r2" name="r" /><label for="r2">Second Radio</label>
</form>
关于javascript - mouseup 后从复选框标签中删除焦点样式的可访问、键盘友好的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46307096/