热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

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

Ihaveanideaforagameinjavascript(ImgoingtomakeitwithEaselJS)andIllhavetodetect

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!

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

4 个解决方案

#1


60  

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/Mozilla_event_reference/keypress
  • https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener
  • https://developer.mozilla.org/en-US/docs/DOM/EventTarget.addEventListener

With jQuery:

使用jQuery:

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

Reference:

参考:

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

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:

这可能有助于决定:

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

#2


11  

KEYPRESS
(enter key)

KEYPRESS(输入密钥)

Vanilla:

香草:

document.addEventListener("keypress", function(event) {
    if (event.keyCode == 13) {
        alert('hi.')
    }
})

Vanilla shorthand:

香草速记:

this.addEventListener('keypress', (event) => {
    if (event.keyCode == 13) {
        alert('hi.')
    }
})

jQuery:

jQuery的:

$(this).on('keypress', function(event) {
    if (event.keyCode == 13) {
        alert('hi.')
    }
})

jQuery classical:

jQuery经典:

$(this).keypress(function(event) {
    if (event.keyCode == 13) {
        alert('hi.')
    }
})

jQuery shorthand:

jQuery简写:

$(this).keypress((e) => {
    if (e.which == 13) {
        alert('hi.')
    }
})

Even shorter:

更短:

$(this).keypress(e=>
    e.which==13?
    alert('hi.'):null
)

demo

演示

#3


6  

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

#4


3  

Use event.key and modern JS!

No number codes anymore. 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...
    }
});

Mozilla Docs

Mozilla文档

Supported Browsers

支持的浏览器


推荐阅读
  • 本文介绍了前端人员必须知道的三个问题,即前端都做哪些事、前端都需要哪些技术,以及前端的发展阶段。初级阶段包括HTML、CSS、JavaScript和jQuery的基础知识。进阶阶段涵盖了面向对象编程、响应式设计、Ajax、HTML5等新兴技术。高级阶段包括架构基础、模块化开发、预编译和前沿规范等内容。此外,还介绍了一些后端服务,如Node.js。 ... [详细]
  • 本文总结了在编写JS代码时,不同浏览器间的兼容性差异,并提供了相应的解决方法。其中包括阻止默认事件的代码示例和猎取兄弟节点的函数。这些方法可以帮助开发者在不同浏览器上实现一致的功能。 ... [详细]
  • Vue基础一、什么是Vue1.1概念Vue(读音vjuː,类似于view)是一套用于构建用户界面的渐进式JavaScript框架,与其它大型框架不 ... [详细]
  • 关于extjs开发实战pdf的信息
    本文目录一览:1、extjs实用开发指南2、本 ... [详细]
  • HowcanIaligntwoinline-blockssothatoneisleftandtheotherisrightonthesameline?Whyi ... [详细]
  •   html5中template用法,html5标签  一、HTML5template元素初面  模板元素,基本上可以确定 ... [详细]
  • javascript – 关于微信浏览器的疑问
    后端开发|php教程php,javascript,html5后端开发-php教程现在正在开发移动端webapp,遇到了比较麻烦的问题:用户输入帐号密码登陆后,自动跳转到首页,,QQ ... [详细]
  • Linux重启网络命令实例及关机和重启示例教程
    本文介绍了Linux系统中重启网络命令的实例,以及使用不同方式关机和重启系统的示例教程。包括使用图形界面和控制台访问系统的方法,以及使用shutdown命令进行系统关机和重启的句法和用法。 ... [详细]
  • IjustinheritedsomewebpageswhichusesMooTools.IneverusedMooTools.NowIneedtoaddsomef ... [详细]
  • jQuery实现简单的动画效果及用法详解
    本文详细介绍了使用jQuery实现简单动画效果的方法,包括显示/隐藏、向上收缩/向下展开、淡入/淡出、自定义动画等。同时提供了具体的用法示例,并解释了参数的含义和使用技巧。通过本文的学习,读者可以掌握如何使用jQuery实现各种动画效果,为网页增添生动和互动性。 ... [详细]
  • 本文介绍了利用ARMA模型对平稳非白噪声序列进行建模的步骤及代码实现。首先对观察值序列进行样本自相关系数和样本偏自相关系数的计算,然后根据这些系数的性质选择适当的ARMA模型进行拟合,并估计模型中的位置参数。接着进行模型的有效性检验,如果不通过则重新选择模型再拟合,如果通过则进行模型优化。最后利用拟合模型预测序列的未来走势。文章还介绍了绘制时序图、平稳性检验、白噪声检验、确定ARMA阶数和预测未来走势的代码实现。 ... [详细]
  • Introduction(简介)Forbeingapowerfulobject-orientedprogramminglanguage,Cisuseda ... [详细]
  • 工作经验谈之-让百度地图API调用数据库内容 及详解
    这段时间,所在项目中要用到的一个模块,就是让数据库中的内容在百度地图上展现出来,如经纬度。主要实现以下几点功能:1.读取数据库中的经纬度值在百度上标注出来。2.点击标注弹出对应信息。3 ... [详细]
  • XMLhttpREquest_Ajax技术总结之XmlHttpRequest
    Ajax1、 什么是ajax   ... [详细]
  • 我正在尝试使用scrapycrallsingle运行完美运行的scrapy蜘蛛,但我无法在python脚本中运行它.主要问题是从不执行SingleBlogSpider.parse方 ... [详细]
author-avatar
欣仪威侑扬芸_782
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有