javascript - mouseup 后从复选框标签中删除焦点样式的可访问、键盘友好的方法

标签 javascript jquery html css

我设置了 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/

相关文章:

javascript - TH 中的自定义悬停

javascript - 将事件处理程序分配给 for 循环中的每个按钮

javascript - 创建多个图像 slider

javascript - 使用 Angular Directive(指令)

html - 如何移动位置为 :relative above div with position:absolute? 的 div

html - 文本区域中的换行符被忽略

javascript - 在特定实例上按下 ESC 键时关闭 jQuery 弹出窗口

javascript - 将鼠标悬停在标签类上更改不同元素中 img 的图像 src

php - 无法使用ajax将数据插入数据库

javascript - 验证如何运作