具有键盘导航支持的自定义HTML复选框符号?

时间:2014-04-12 21:00:36

标签: html css checkbox keyboard accessibility

我可以替换传统的HTML复选框符号“unchecked”,“checked”和 使用自定义符号“不确定”:

<link rel="stylesheet" 
  href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">
<style type="text/css">
  input[type="checkbox"] {
    display: none;
  }
  input[type="checkbox"]+label:before {
    font-family: FontAwesome;
    content: "\f096"; /* fa-square-o */
  }
  input[type="checkbox"]:checked + label:before {
    content: "\f046"; /* fa-check-square-o */
  }
  input[type="checkbox"]:indeterminate + label:before {
    content: "\f0c8"; /* fa-square */
    color: grey;
  }
</style>
...
<input type="checkbox" id="cb1" />
<label for="cb1"> label text</label>

请参阅http://plnkr.co/SPvN1xEkQqcFcYbxWur2

除键盘导航和控制外,此功能非常有用。使用传统的复选框,您可以[TAB]通过输入元素和链接,并使用[SPACE]和[ENTER]访问它们。自定义符号使用 display:none ,这似乎禁用了这些元素的键盘控制。

如何为这些自定义复选框重新启用键盘控制?

1 个答案:

答案 0 :(得分:5)

不是将复选框设置为display: none,而是将其隐藏在后面。你仍然可以使用tab来聚焦并保留其他键盘事件。

<link rel="stylesheet" href="//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.css">
<style type="text/css">
  input[type="checkbox"] {
    position:absolute;
    margin: 2px 0 0;
    z-index:0;
  }

  input[type="checkbox"]+label:before {
    position: relative;
    z-index: 5;
    background: white;
    font-family: FontAwesome;
    content: "\f096";
  }

  input[type="checkbox"]:checked + label:before {
    position: relative;
    z-index: 5;
    background: white;
    content: "\f046";
  }

  input[type="checkbox"]:indeterminate + label:before {
    position: relative;
    z-index: 5;
    background: white;
    content: "\f0c8";
    color: grey;
  }
</style>
...
<input type="checkbox" id="cb1" />
<label for="cb1"> label text</label>

实例:http://plnkr.co/edit/6lzcJIdMWFRzVNQBxRPu?p=preview