[英]How to allow the user to press a button by both clicking on it or by pressing the space bar
I have created a device where the user can click on the on and off button to turn it on and off. 我创建了一个设备,用户可以单击打开和关闭按钮将其打开和关闭。 I also want the user to be able to do the same by pressing the spacebar on the keyboard but am having some trouble.
我还希望用户能够通过按键盘上的空格键来执行相同操作,但是遇到了一些麻烦。 Also I'm new to javascript and this site so please forgive me for any mistakes.
我也是javascript和这个网站的新手,所以如有任何错误,请原谅我。
let buttons1=document.querySelectorAll(".col-6"); for(let i=0; i<buttons1.length; i++){ buttons1[i].onclick=function(){ document.body.onkeyup = function(e){ if(buttons1[i].innerHTML=='ON / OFF'||e.keyCode==32){ ...rest of my code....
You could try something like this: 您可以尝试这样的事情:
let buttonState = false; document.getElementById("status").innerHTML = JSON.stringify(buttonState); document.body.onkeyup = function(e) { // if space bar pressed if (e.keyCode == 32 || e.key === ' ') { toggleState(); } } function toggleState () { // toggle button state buttonState = !buttonState; document.getElementById("status").innerHTML = JSON.stringify(buttonState); }
<button type="button" onclick="toggleState()"> Toggle On/Off </button> <div id="status"></div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.