gpt4 book ai didi

javascript - 要选中/取消选中按键盘上的输入或空格键的复选框?

转载 作者:行者123 更新时间:2023-11-28 03:54:40 24 4
gpt4 key购买 nike

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

最佳答案

您可以试试这个自定义复选框,适用于空格键但不适用于回车键。 https://codepen.io/CreativeJuiz/pen/BiHzp

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

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

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com