[英]How to allow the user to press a button by both clicking on it or by pressing the space bar
我創建了一個設備,用戶可以單擊打開和關閉按鈕將其打開和關閉。 我還希望用戶能夠通過按鍵盤上的空格鍵來執行相同操作,但是遇到了一些麻煩。 我也是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....
您可以嘗試這樣的事情:
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.