jQuery 在javascript中检测按键的最简单方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16089421/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Simplest way to detect keypresses in javascript
提问by bobismijnnaam
I have an idea for a game in javascript (I'm going to make it with EaselJS) and I'll have to detect keypresses. After looking around on the internet I've seen a lot of suggestions (use window.onkeypress, use jQuery, etc.) but for almost every option there's a counterargument. What do you guys suggest? Using jQuery for this sounds easy enough but I have virtually no experience with that library (and I'm not particulary a veteran at javascript either) so I'd rather avoid it. If jQuery is the best option, can someone give a good example (with explanation would be awesome) of how to do this?
我有一个用 javascript 编写游戏的想法(我将用 EaselJS 制作它),我必须检测按键。在互联网上环顾四周后,我看到了很多建议(使用 window.onkeypress、使用 jQuery 等),但几乎每个选项都有一个反驳。你们有什么建议?为此使用 jQuery 听起来很容易,但我几乎没有使用该库的经验(而且我也不是 javascript 的资深人士)所以我宁愿避免它。如果 jQuery 是最好的选择,有人可以举一个很好的例子(解释会很棒)如何做到这一点?
I guess this gets asked a lot but I couldn't find any clear answers. Thanks in advance!
我想这被问了很多,但我找不到任何明确的答案。提前致谢!
回答by Ian
With plain Javascript, the simplest is:
使用普通的 Javascript,最简单的是:
document.onkeypress = function (e) {
e = e || window.event;
// use e.keyCode
};
But with this, you can only bind one handler for the event.
但是有了这个,您只能为事件绑定一个处理程序。
In addition, you could use the following to be able to potentially bind multiple handlers to the same event:
此外,您可以使用以下内容将多个处理程序潜在地绑定到同一事件:
addEvent(document, "keypress", function (e) {
e = e || window.event;
// use e.keyCode
});
function addEvent(element, eventName, callback) {
if (element.addEventListener) {
element.addEventListener(eventName, callback, false);
} else if (element.attachEvent) {
element.attachEvent("on" + eventName, callback);
} else {
element["on" + eventName] = callback;
}
}
In either case, keyCode
isn't consistent across browsers, so there's more to check for and figure out. Notice the e = e || window.event
- that's a normal problem with Internet Explorer, putting the event in window.event
instead of passing it to the callback.
在任何一种情况下,keyCode
浏览器之间都不一致,因此需要检查和找出更多内容。请注意e = e || window.event
- 这是 Internet Explorer 的正常问题,将事件放入window.event
而不是将其传递给回调。
References:
参考:
- https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keypress
- https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
- https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keypress
- https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
With jQuery:
使用 jQuery:
$(document).on("keypress", function (e) {
// use e.which
});
Reference:
参考:
Other than jQuery being a "large" library, jQuery really helps with inconsistencies between browsers, especially with window events...and that can't be denied. Hopefully it's obvious that the jQuery code I provided for your example is much more elegant and shorter, yet accomplishes what you want in a consistent way. You should be able to trust that e
(the event) and e.which
(the key code, for knowing which key was pressed) are accurate. In plain Javascript, it's a little harder to know unless you do everything that the jQuery library internally does.
除了 jQuery 是一个“大型”库之外,jQuery 确实有助于解决浏览器之间的不一致问题,尤其是窗口事件……这是不可否认的。希望很明显,我为您的示例提供的 jQuery 代码更加优雅和简短,但以一致的方式完成了您想要的工作。您应该能够相信e
(事件)和e.which
(键代码,用于了解按下了哪个键)是准确的。在普通的 Javascript 中,除非您完成 jQuery 库内部所做的一切,否则很难知道。
Note there is a keydown
event, that is different than keypress
. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown
请注意,有一个keydown
事件,与keypress
. 您可以在此处了解有关它们的更多信息:onKeyPress Vs。onKeyUp 和 onKeyDown
As for suggesting what to use, I would definitely suggest using jQuery if you're up for learning the framework. At the same time, I would say that you should learn Javascript's syntax, methods, features, and how to interact with the DOM. Once you understand how it works and what's happening, you should be more comfortable working with jQuery. To me, jQuery makes things more consistent and is more concise. In the end, it's Javascript, and wraps the language.
至于建议使用什么,如果您准备学习该框架,我肯定会建议使用 jQuery。同时,我会说你应该学习Javascript的语法、方法、特性以及如何与DOM交互。一旦你理解了它是如何工作的以及发生了什么,你应该更习惯使用 jQuery。对我来说,jQuery 使事情更加一致并且更加简洁。最后,它是 Javascript,并包装了语言。
Another example of jQuery being very useful is with AJAX. Browsers are inconsistent with how AJAX requests are handled, so jQuery abstracts that so you don't have to worry.
jQuery 非常有用的另一个例子是 AJAX。浏览器与 AJAX 请求的处理方式不一致,因此 jQuery 将其抽象化,因此您不必担心。
Here's something that might help decide:
以下内容可能有助于您做出决定:
回答by Thielicious
KEYPRESS(enter key)
Click inside the results frame before you press the key.
KEYPRESS(输入键)
在按下键之前在结果框内单击。
Vanilla
香草
document.addEventListener("keypress", function(event) {
if (event.keyCode == 13) {
alert('hi.');
}
});
Vanilla shorthand(ES6)
香草速记(ES6)
this.addEventListener('keypress', event => {
if (event.keyCode == 13) {
alert('hi.')
}
})
jQuery
jQuery
$(this).on('keypress', function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jQuery classic
jQuery 经典
$(this).keypress(function(event) {
if (event.keyCode == 13) {
alert('hi.')
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
jQuery shorthand(ES6)
jQuery 速记(ES6)
$(this).keypress((e) => {
if (e.keyCode == 13)
alert('hi.')
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Even shorter(ES6)
更短(ES6)
$(this).keypress(e=>
e.which==13?
alert`hi.`:null
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Due some requests, here an explanation:
由于一些要求,这里有一个解释:
I rewrote this answer as things have become deprecated over time so I updated it.
我重写了这个答案,因为随着时间的推移,事情已经被弃用了,所以我更新了它。
I used this
to focus on the window scope inside the results when document is ready and for the sake of brevity but it's not necessary.
this
当文档准备好时,为了简洁起见,我过去常常关注结果中的窗口范围,但这不是必需的。
Deprecated:
The .which
and .keyCode
methods are actually considered deprecated so I would recommend .code
but I personally still use keyCode as the performance is much faster and only that counts for me.
The jQuery classic version .keypress()
is not officially deprecated as some people say but they are no more preferred like .on('keypress')
as it has a lot more functionality(live state, multiple handlers, etc.).
The 'keypress'
event in the Vanilla version is also deprecated. People should prefer beforeinputor keydowntoday. (Note: It has nothing to do with jQuery's events, they are called the same but execute differently.)
推荐使用:
将.which
和.keyCode
方法实际上被废弃了,所以我会建议.code
,但我个人仍然使用键代码为性能更快,只为我计数。jQuery 经典版本.keypress()
并未像某些人所说的那样正式弃用,但它们不再受青睐,.on('keypress')
因为它具有更多功能(实时状态、多个处理程序等)。'keypress'
Vanilla 版本中的事件也已弃用。今天人们应该更喜欢beforeinput或keydown。(注意:它与 jQuery 的事件无关,它们被称为相同但执行不同。)
All examples above are no biggies regarding deprecated or not. Consoles or any browser should be able to notify you with that if this happens. And if this ever does in future, just fix it.
上面的所有示例都没有关于弃用与否的大问题。如果发生这种情况,控制台或任何浏览器应该能够通知您。如果将来会发生这种情况,请修复它。
Readablity:
Despite the ease making it too short and snippy isn't always good either. If you work in a team, your code must be readable and detailed. I recommend the jQuery version .on('keypress')
, this is the way to go and understandable by most people.
可读性:
尽管很容易让它太短而且时髦也不总是好的。如果您在团队中工作,您的代码必须可读且详细。我推荐 jQuery 版本.on('keypress')
,这是大多数人可以理解的方式。
Performance:
I always follow my phrase Performance over Effectivenessas anything can be more effective if there is the option but it just should function and execute only what I want, the faster the better. This is why I prefer .keyCode
even if it's considered deprecated(in most cases). It's all up to you though.
性能:
我总是遵循我的短语性能胜过有效性,因为如果有选择,任何事情都可以更有效,但它应该只运行并执行我想要的东西,越快越好。这就是为什么我更喜欢.keyCode
即使它被认为已弃用(在大多数情况下)。不过这一切都取决于你。
回答by Gibolt
Use event.key
and modern JS!
使用event.key
和现代JS!
No number codesanymore. You can use "Enter"
, "ArrowLeft"
, "r"
, or any key name directly, making your code far more readable.
没有数字代码了。您可以直接使用"Enter"
、"ArrowLeft"
、"r"
或任何键名,使您的代码更具可读性。
document.addEventListener("keypress", function onEvent(event) {
if (event.key === "ArrowLeft") {
// Move Left
}
else if (event.key === "Enter") {
// Open Menu...
}
});
回答by faino
There are a few ways to handle that; Vanilla JavaScript can do it quite nicely:
有几种方法可以处理;Vanilla JavaScript 可以很好地做到这一点:
function code(e) {
e = e || window.event;
return(e.keyCode || e.which);
}
window.onload = function(){
document.onkeypress = function(e){
var key = code(e);
// do something with key
};
};
Or a more structured way of handling it:
或者更结构化的处理方式:
(function(d){
var modern = (d.addEventListener), event = function(obj, evt, fn){
if(modern) {
obj.addEventListener(evt, fn, false);
} else {
obj.attachEvent("on" + evt, fn);
}
}, code = function(e){
e = e || window.event;
return(e.keyCode || e.which);
}, init = function(){
event(d, "keypress", function(e){
var key = code(e);
// do stuff with key here
});
};
if(modern) {
d.addEventListener("DOMContentLoaded", init, false);
} else {
d.attachEvent("onreadystatechange", function(){
if(d.readyState === "complete") {
init();
}
});
}
})(document);
回答by Coder Gautam YT
Don't over complicate.
不要过于复杂。
document.addEventListener('keydown', logKey);
function logKey(e) {
if (`${e.code}` == "ArrowRight") {
//code here
}
if (`${e.code}` == "ArrowLeft") {
//code here
}
if (`${e.code}` == "ArrowDown") {
//code here
}
if (`${e.code}` == "ArrowUp") {
//code here
}
}