是否可以触发不在输入或textarea标签中的javascript按键事件?

时间:2016-07-16 19:09:00

标签: javascript events keypress

我想知道你是否可以触发javacript按键事件而不是输入textarea标签?

我想要实现的目标是当用户按下页面上任何位置的任何键时,警告会显示:您按了一个键。

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

function pushbtn(event){
var x = event.keyCode;
alert("You pressed"+x)
}

我不确定要使用事件监听器还是应该放置它。

4 个答案:

答案 0 :(得分:1)

您可以通过在文档上添加事件侦听器来完成此操作。

    function pushbtn (event){
      var x = event.charCode; //not keyCode
      alert("You pressed"+x);
    }

    //adding event listner on document
    document.addEventListener('keypress', pushbtn); 

使用charCode代替keyCode但仍然keyCode会为您提供密钥的密钥代码(数字) 使用key它非常适合您的情况。 代码看起来像这样

    function pushbtn (event){
      var x = event.key;
      alert("You pressed :"+x);
    }

    //adding event listner on document
    document.addEventListener('keypress', pushbtn); 

答案 1 :(得分:0)

当然,您可以将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);
body,
html {
  height: 100vh;
  width: 100vw;
  margin: 0;
  background-color: #f00;
}

如果您希望排除在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);
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;
}
<input />
<textarea></textarea>

答案 2 :(得分:0)

也许:

document.onkeypress = function(event){

if(event.keyCode == 32){
document.write("Space key pressed");
};

};

当然,您可以根据所需的密钥更改keyCode,或者如果您不关心按下哪个键,则删除整个keyCode部分。

希望它有所帮助;)

答案 3 :(得分:0)

将整个文档添加为事件目标,然后将其附加到JavaScript或jQuery keypress事件侦听器。

from game.ui import data as ui_data