要选中/取消选中要在键盘中输入还是空格键的复选框?

时间:2017-04-21 09:31:40

标签: javascript html css

我有一个看起来像单选按钮的复选框,它实际上是一个css背景图像。对于这个元素,我希望用户能够使用空格键或键盘输入键来检查或取消选中它。

在span元素中,我尝试了一个onkeypress函数

这是我的代码:

<span class=" " role="checkbox" tabindex="0" onKeypress="myFunction(event)"

    function myFucntion(event) {

      var node = event.currentTarget


      var state = node.getAttribute('aria-checked').toLowerCase()

      if (event.type === 'click' || 
          (event.type === 'keydown' && event.keyCode === 32)
          ) {
              if (state === 'true') {
                node.setAttribute('aria-checked', 'false')

              }
              else {
                node.setAttribute('aria-checked', 'true')

              }  

        event.preventDefault()
        event.stopPropagation()
      }

    }

我从https://www.w3.org/TR/2016/WD-wai-aria-practices-1.1-20160317/examples/checkbox/checkbox-1.html

尝试了这个逻辑
  My question is 1) how do i change the image when the user checks/unchecks it
                   2) how to handle the spacebar/enter keycodes
                   3) how to store image inside a javascript variable
    Apologies for not being able to put the proper code,this is just partial one,but any kind of help would be highly appreciated.

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此自定义复选框,适用于空格键但不适用于输入键。 https://codepen.io/CreativeJuiz/pen/BiHzp

<form action="#">
  <p>
    <input type="checkbox" id="test1" />
    <label for="test1">Red</label>
  </p>
  <p>
</form>