如何使用硬件键盘按键触发html按钮及其onclick功能?

时间:2019-10-22 22:29:24

标签: javascript button onclick addeventlistener

我是编码的新手,这个话题可能很常见,但是我很困惑。

我有一个按钮<button onclick = typeWriter()>/click</button>

我的功能:var myArray = ['such', 'something else', ]; var rand = myArray[Math.floor(Math.random() * myArray.length)]; var i = 0; var speed = 55; function typeWriter() { if (i < rand.length) { document.getElementById("question").innerHTML += rand.charAt(i); i++; setTimeout(typeWriter, speed); } }

如何添加空格键作为事件监听器或类似的键盘键,以便当我按下空格键(而不是在文本框中)时,它按下按钮并触发功能?一个简单的普通javascript答案会比较可取,因为我没有jQuery。

最好只添加用空格键触发myFunction的脚本,而不是触发按钮?如果是这样,我该如何编程?

顺便说一句:我正在尝试使用iPad键盘在移动设备上执行此操作。这会改变什么吗?

谢谢。

2 个答案:

答案 0 :(得分:0)

如果要在HTML的所有位置触发函数,可以在window上添加侦听器。

window.onkeydown = function(event) {
    if (event.keyCode == 32) {
        //your function here
    };
};

在这里您可以找到键盘的所有键代码:https://keycode.info/

答案 1 :(得分:0)

  • 不要使用内联JS
  • 使用addEventListener()
  • 使用Event.key确定按下的键
  • 使用辅助函数来确定当前Event.target是否为FormElement

// Function to detect if el is a form element
const isFormElement = el => /^(input|textarea|select|button)$/i.test(el.nodeName);

// Example function
const myFunction = ev => console.log("HELLO!");

// Find buttons in DOM
const EL_myfn = document.querySelectorAll('.js-myFunction');

// Trigger directly on buttons click
EL_myfn.forEach(el=> el.addEventListener('click', myFunction));

// And on keydown
window.addEventListener('keydown', ev => {
  // If spacebar is hit, and we're not inside a forminput element
  if (ev.key === " " && !isFormElement(ev.target)) {
    myFunction();
  }
})
textarea{width: 100%;}
<button class="js-myFunction">Click me! (Console  should log)</button>
<div>press spacebar here (Console should log)</div>
<textarea>press spacebar here (Console should not log!!)</textarea>