如何在键盘上的键盘按键上调用javascript事件?

时间:2017-08-11 13:27:27

标签: javascript

我对Javascript很新,基本上我想在键盘上的按键功能键上调用一个简单的javascript事件。下面的代码提供了点击按钮的当前日期和时间,同样我们可以在按键功能键上调用javascript事件吗?



<input type = "text" onkeypress="document.getElementById('demo').innerHTML=Date()">The time is?

<p id="demo"></p>
&#13;
&#13;
&#13;

2 个答案:

答案 0 :(得分:0)

非常简单,有一个onkeypress事件:

&#13;
&#13;
<button onkeypress="document.getElementById('demo').innerHTML=Date()">The time is?</button>

<p id="demo"></p>
&#13;
&#13;
&#13;

我认为这不需要解释。

答案 1 :(得分:0)

您只需要使用事件监听器,然后按密钥代码对其进行过滤。

document.addEventListener("keydown", function(event) {
  event.preventDefault();
  switch (event.which) {
    case 112:
      setMessage("You just pressed F1!");
      break;
    case 113:
      setMessage("You just pressed F2!");
      break;
    case 114:
      setMessage("You just pressed F3!");
      break;
    case 115:
      setMessage("You just pressed F4!");
      break;
    case 116:
      setMessage("You just pressed F5!");
      break;
    case 117:
      setMessage("You just pressed F6!");
      break;
    case 118:
      setMessage("You just pressed F7!");
      break;
    case 119:
      setMessage("You just pressed F8!");
      break;
    case 120:
      setMessage("You just pressed F9!");
      break;
    case 121:
      setMessage("You just pressed F10!");
      break;
    case 122:
      setMessage("You just pressed F11!");
      break;
    case 123:
      setMessage("You just pressed F12!");
      break;
  }
})

function setMessage(msg) {
  document.querySelector('.demo').innerHTML = msg;
}
<div class="demo">Press a function button</div>