在javascript中检测按键的最简单方法

2023-03-15前端开发问题
5

本文介绍了在javascript中检测按键的最简单方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我有一个 javascript 游戏的想法(我将使用 EaselJS 制作它),我必须检测按键.在互联网上环顾四周后,我看到了很多建议(使用 window.onkeypress,使用 jQuery 等),但几乎每个选项都有反驳.你们有什么建议?使用 jQuery 听起来很容易,但我几乎没有使用该库的经验(而且我也不是 javascript 的资深人士)所以我宁愿避免使用它.如果 jQuery 是最好的选择,有人可以举一个很好的例子(解释会很棒)吗?

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?

我想这被问了很多,但我找不到任何明确的答案.提前致谢!

I guess this gets asked a lot but I couldn't find any clear answers. Thanks in advance!

推荐答案

用纯Javascript,最简单的是:

With plain Javascript, the simplest is:

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;
    }
}

在任何一种情况下,keyCode 在浏览器中都不一致,因此需要检查和找出更多内容.注意 e = e ||window.event - 这是 Internet Explorer 的正常问题,将事件放在 window.event 中,而不是将其传递给回调.

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.

参考资料:

  • https://developer.mozilla.org/en-US/docs/DOM/Mozilla_event_reference/keypress
  • https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener

使用 jQuery:

$(document).on("keypress", function (e) {
    // use e.which
});

参考:

  • http://api.jquery.com/on/

除了 jQuery 是一个大型"库之外,jQuery 确实有助于解决浏览器之间的不一致问题,尤其是窗口事件……这是不可否认的.希望很明显,我为您的示例提供的 jQuery 代码更优雅、更短,但以一致的方式完成了您想要的工作.您应该能够相信 e (事件)和 e.which (键码,用于知道按下了哪个键)是准确的.在纯 Javascript 中,除非您执行 jQuery 库内部所做的所有事情,否则很难知道.

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.

注意有一个 keydown 事件,它不同于 keypress.您可以在此处了解有关它们的更多信息:onKeyPress Vs.onKeyUp 和 onKeyDown

Note there is a keydown event, that is different than keypress. You can learn more about them here: onKeyPress Vs. onKeyUp and onKeyDown

至于建议使用什么,如果您准备学习该框架,我肯定会建议使用 jQuery.同时,我想说你应该学习 Javascript 的语法、方法、特性,以及如何与 DOM 交互.一旦你理解了它是如何工作的以及发生了什么,你应该更容易使用 jQuery.对我来说,jQuery 让事情变得更加一致和简洁.最后,它是 Javascript,并包装了语言.

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 例子是 AJAX.浏览器与 AJAX 请求的处理方式不一致,因此 jQuery 抽象了这一点,因此您不必担心.

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.

以下几点可能有助于做出决定:

Here's something that might help decide:

  • http://www.jscripters.com/jquery-disadvantages-and-advantages/

这篇关于在javascript中检测按键的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

js删除数组中指定元素的5种方法
在JavaScript中,我们有多种方法可以删除数组中的指定元素。以下给出了5种常见的方法并提供了相应的代码示例: 1.使用splice()方法: let array = [0, 1, 2, 3, 4, 5];let index = array.indexOf(2);if (index -1) { array.splice(index, 1);}// array = [0,...
2024-11-22 前端开发问题
182

layui 实现实时刷新一个外部的div
主页面上显示了一个合计,在删除和增加的时候需要更改这个总套数的值: //html代码div class="layui-inline layui-show-xs-block" style="margin-left: 10px" id="sumDiv"spanSOP合计:/spanspan${totalNum}/spanspan套/span/div 于是在我们删除这个条数据后,...
2024-11-14 前端开发问题
156

layui要如何改变时间日历布局大小?
问题描述 我想改变layui时间日历布局大小,这个要怎么操作呢? 解决办法 可以用css样式对时间日历进行重新布局,具体代码如下: !DOCTYPE htmlhtmlheadmeta charset="UTF-8"title/titlelink rel="stylesheet" href="../../layui/css/layui.css" /style#test-...
2024-10-24 前端开发问题
271

layui中表单会自动刷新的问题
layui中表单会自动刷新的问题,因为用到layui的表单,遇到了刷新的问题所以记录一下: script layui.use(['jquery','form','layer'], function(){ var $ = layui.jquery, layer=layui.layer, form = layui.form; form.on('submit(tijiao)', function(data){ a...
2024-10-23 前端开发问题
262

JavaScript小数运算出现多位的解决办法
在开发JS过程中,会经常遇到两个小数相运算的情况,但是运算结果却与预期不同,调试一下发现计算结果竟然有那么长一串尾巴。如下图所示: 产生原因: JavaScript对小数运算会先转成二进制,运算完毕再转回十进制,过程中会有丢失,不过不是所有的小数间运算会...
2024-10-18 前端开发问题
301

jQuery怎么动态向页面添加代码?
append() 方法在被选元素的结尾(仍然在内部)插入指定内容。 语法: $(selector).append( content ) var creatPrintList = function(data){ var innerHtml = ""; for(var i =0;i data.length;i++){ innerHtml +="li class='contentLi'"; innerHtml +="a href...
2024-10-18 前端开发问题
125