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

时间:2017-04-18 05:18:41

标签: html css checkbox

我在this site上创建了一个自定义复选框,我正在尝试将它与tabindex一起使用,但我知道这个CSS使用的return request .then(result => { console.log(result); return result; }) .catch(error => { console.error(error); throw error; }); 并不允许使用taborder,所以这是我的问题:如何在保留输入属性的同时在表单中使用此自定义复选框?

1 个答案:

答案 0 :(得分:1)

您可以将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>
&#13;
&#13;
&#13;