[英]Reacting when user presses ENTER
I'm working on an application where it should be possible to run a function if the user presses ENTER regardless of where the focus is on the page (eg. in a textbox or on a button etc). 我正在开发一个应用程序,无论用户焦点在页面上的什么位置(例如,在文本框或按钮等位置),只要用户按ENTER都应该可以运行功能。
Below is the code i've experimented with, just to find out how to react when the user presses ENTER , but it doesn't work. 下面是我尝试过的代码,目的只是为了找出当用户按下ENTER时如何做出反应,但这是行不通的。 What am I doing wrong?
我究竟做错了什么? Thanks in advance!
提前致谢!
var Capsule = {
init: function() {
var button = document.getElementById("txtInput");
button.focus();
Capsule.events();
},
events: function() {
function checkKeyboard(e) {
if (e.keyCode == 13) {
console.log("Pressed ENTER.");
return false;
}
}
}
}
window.onload = Capsule.init;
You have to bind the event as well.. 您还必须绑定事件。
onkeydown
- if you want to capture the event right after the key has pressed down. onkeydown
如果您想在按下键后立即捕获事件。 onkeypress
- if you want to capture each keystroke while holding the key pressed. onkeypress
如果要在按住键的同时捕获每个按键。 onkeyup
- If you want to capture the event right after lifting the key. onkeyup
如果您想在举起钥匙后立即捕获事件。 Since you're using return false;
由于您使用
return false;
(I recommend e.preventDefault()
, you're probably looking for onkeydown
or onkeypress
. The default action cannot be prevented at onkeyup
, because the default behaviour has already occurred. (我建议使用
e.preventDefault()
,您可能正在寻找onkeydown
或onkeypress
。无法在onkeyup
阻止默认操作,因为已经发生了默认行为。
Code: 码:
events: function() {
function checkKeyboard(e) {
if (e.keyCode == 13) {
console.log("Pressed ENTER.");
return false;
}
}
window.onkeypress = checkKeyboard; //Or: document.onkeypress = ..
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.