当用户按下 ENTER 时做出反应
我正在开发一个应用程序,如果用户按 ENTER ,无论焦点位于页面上的哪个位置(例如在文本框中),都应该可以运行一个函数或按钮等)。
下面是我尝试过的代码,只是为了了解当用户按 ENTER 时如何反应,但它不起作用。我做错了什么?提前致谢!
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;
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).
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. 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;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您还必须绑定事件。
onkeydown
- 如果您想在按下按键后立即捕获事件。onkeypress
- 如果您想在按住按键的同时捕获每次击键。onkeyup
- 如果您想在抬起按键后立即捕获事件。由于您使用的是
return false;
(我推荐e.preventDefault()
),您可能正在寻找onkeydown
或onkeypress
无法在onkeyup
处阻止默认操作,因为默认行为已经发生。
You have to bind the event as well..
onkeydown
- if you want to capture the event right after the key has pressed down.onkeypress
- if you want to capture each keystroke while holding the key pressed.onkeyup
- If you want to capture the event right after lifting the key.Since you're using
return false;
(I recommende.preventDefault()
, you're probably looking foronkeydown
oronkeypress
. The default action cannot be prevented atonkeyup
, because the default behaviour has already occurred.Code: