我有一个看起来像单选按钮的复选框,实际上是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.

最佳答案

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

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

关于javascript - 要在点击键盘上的Enter键或空格键时选中/取消选中复选框?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43539044/

10-12 12:46
查看更多