简体   繁体   English

如何允许用户通过单击按钮或按下空格键来按下按钮

[英]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.

相关问题 为什么模态弹出按下空格键? 我该如何预防? - Why does modal pop up pressing space bar press? How do I prevent it? 在手机上将按空格键更改为屏幕上的按钮 - Change Press Space Bar to Onscreen Button on Mobile Reactjs 当按下空格键而不是在按钮上时触发带有 keydown 的按钮 - Reactjs trigger button with keydown when pressing space bar not on the button 按下回车键或单击按钮时如何创建一个按钮来执行代码? - How to Create a button to execute code when pressing enter or clicking the button? 当用户按下“空格键”时删除事件监听器 - Remove event listeners when user press 'space bar' 如何在 vuejs 中按下按钮时删除空间? - How to remove space during button press in vuejs? jQuery:如何在按下Enter键或单击按钮时触发Click事件 - Jquery: how to trigger click event on pressing enter key or clicking button 如何在单击按钮并按 Enter 时启动 jquery 功能 - How can I start a jquery function on clicking a button and on pressing enter 将用户导航到URL并模拟用户按向下箭头或单击按钮3次 - Navigate a user to a URL and simulate the user pressing down arrow or clicking a button 3 times 如何扩展Button组件并允许空间事件 - How to extend Button component and allow space event
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM