html - 如何使用此自定义复选框保持 Tab 键行为?

标签 html css checkbox

我在 this site 上创建了一个自定义复选框我正在尝试将它与 tabindex 一起使用,但我知道此 CSS 使用 display: none 不允许 taborder,所以这是我的问题:How can I use this custom checkbox in a form同时保持输入的属性?

最佳答案

您可以将 tabindex 附加到代表复选框的标签,然后将键盘事件附加到标签以在按下某个键时切换复选框。在此示例中,我在用户按下空格键时切换它,就像真正的复选框一样。

var checkbox = document.getElementById('myonoffswitch'),
  label = document.querySelector('#myonoffswitch + label');


label.addEventListener('keypress', function (evt) {
  if (evt.key === ' ') {
    checkbox.checked = !checkbox.checked;
  } else if (evt.key === 'Enter') {
    // .form returns a reference to the parent form
    checkbox.form.submit();
  }
}, false);
.onoffswitch {
    position: relative; width: 90px;
    -webkit-user-select:none; -moz-user-select:none; -ms-user-select: none;
}
.onoffswitch-checkbox {
    display: none;
}
.onoffswitch-label {
    display: block; overflow: hidden; cursor: pointer;
    border: 2px solid #999999; border-radius: 20px;
}
.onoffswitch-inner {
    display: block; width: 200%; margin-left: -100%;
    transition: margin 0.3s ease-in 0s;
}
.onoffswitch-inner:before, .onoffswitch-inner:after {
    display: block; float: left; width: 50%; height: 30px; padding: 0; line-height: 30px;
    font-size: 14px; color: white; font-family: Trebuchet, Arial, sans-serif; font-weight: bold;
    box-sizing: border-box;
}
.onoffswitch-inner:before {
    content: "";
    padding-left: 10px;
    background-color: #2E8DEF; color: #FFFFFF;
}
.onoffswitch-inner:after {
    content: "";
    padding-right: 10px;
    background-color: #CCCCCC; color: #333333;
    text-align: right;
}
.onoffswitch-switch {
    display: block; width: 25px; margin: 2.5px;
    background: #000000;
    position: absolute; top: 0; bottom: 0;
    right: 56px;
    border: 2px solid #999999; border-radius: 20px;
    transition: all 0.3s ease-in 0s; 
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-inner {
    margin-left: 0;
}
.onoffswitch-checkbox:checked + .onoffswitch-label .onoffswitch-switch {
    right: 0px; 
}
<form id="theform">
<input><br>
<br>
<div class="onoffswitch">
    <input type="checkbox" name="onoffswitch" class="onoffswitch-checkbox" id="myonoffswitch" checked>
    <label class="onoffswitch-label" for="myonoffswitch" tabindex="0">
        <span class="onoffswitch-inner"></span>
        <span class="onoffswitch-switch"></span>
    </label>
</div><br>
<input><br>
<input type="checkbox" id="normal-checkbox"><label for="normal-checkbox">Normal Checkbox</label>
</form>

关于html - 如何使用此自定义复选框保持 Tab 键行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43464148/

相关文章:

javascript - 使用jquery选中复选框时如何制作键值对数组?

php - keyup if 语句的 indexOf 字符串行为很奇怪?

javascript - 我正在尝试在我的 Canvas 中实现撤消选项

javascript - Bootstrap可折叠导航不折叠

html - 进度条-如何添加标记/标线

html - 使用 HTML 和 CSS 创建中心菜单

php - 如果我不选中复选框,则未定义索引

javascript - 在 ui-router 上更改状态时出现 angularjs infdig 错误(带视频)

html - 生成的 CSS3 变换处理矩形

html - 使用按钮标记更改复选框的状态不再有效