是否可以触发不在 input 或 textarea 标签中的 javascript keypress 事件?

Wil*_*ier 3 javascript events keypress

我想知道您是否可以触发 javacript keypress 事件,但不能在 input out textarea 标签内触发?

我想要实现的是,当用户在页面上的任意位置按下任意键时,会出现一个警告:您按下了一个键。

这是我的代码:http : //codepen.io/willydev/pen/LkZAob

function pushbtn(event){
var x = event.keyCode;
alert("You pressed"+x)
}
Run Code Online (Sandbox Code Playgroud)

我不确定要使用事件侦听器还是应该把它放在哪里。

Dav*_*mas 6

当然你可以,简单地将keypress事件处理程序委托给document

function pushbtn(event) {

  // retrieving the keyCode of the pressed key:
  var keycode = event.keyCode,

  // finding which letter was generated, using
  // String.fromCharCode():
    key = String.fromCharCode(keycode);
  console.log('You pressed ' + key + ' (keyCode: ' + keycode + ').');
}

document.addEventListener('keypress', pushbtn);
Run Code Online (Sandbox Code Playgroud)
body,
html {
  height: 100vh;
  width: 100vw;
  margin: 0;
  background-color: #f00;
}
Run Code Online (Sandbox Code Playgroud)

如果您希望排除keypress<input><textarea>元素中触发的事件:

function pushbtn(event) {
  var keycode = event.keyCode,
    key = String.fromCharCode(keycode),

    // finding the element on which the event
    // was originally fired:
    source = event.target,

    // an Array of element-types upon which
    // the function should not fire (to prevent
    // interfering needlessly with the UI and
    // user-expectations):
    exclude = ['input', 'textarea'];

  // finding the element-type (tagName) of the element
  // upon which the event was fired, converting it to
  // a lower-case string and then looking in the Array
  // of excluded elements to see if the element is held
  // within (-1 indicates the string was not found within
  // the Array):
  if (exclude.indexOf(source.tagName.toLowerCase()) === -1) {
    console.log('You pressed ' + key + ' (keyCode: ' + keycode + ').');
  }
  return;
}

document.addEventListener('keypress', pushbtn);
Run Code Online (Sandbox Code Playgroud)
body,
html {
  height: 100vh;
  width: 100vw;
  margin: 0;
  background-color: #f00;
}
input,
textarea {
  display: block;
  width: 30%;
  box-sizing: border-box;
  margin: 0.5em 0 0 1em;
}
Run Code Online (Sandbox Code Playgroud)
<input />
<textarea></textarea>
Run Code Online (Sandbox Code Playgroud)

  • 赞成,但这似乎有点过时:根据 MDN,“keypress”事件已被弃用,取而代之的是“keydown”和/或“keyup”。此外,MDN 指出“event.keyCode”已被弃用,取而代之的是“event.key”。 (2认同)