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

检查钥匙是否丢失?-Checkifakeyisdown?

IsthereawaytodetectifakeyiscurrentlydowninJavaScript?是否有一种方法可以检测一个键是否在JavaScript中当前处于关

Is there a way to detect if a key is currently down in Javascript?

是否有一种方法可以检测一个键是否在Javascript中当前处于关闭状态?

I know about the "keydown" event, but that's not what I need. Some time AFTER the key is pressed, I want to be able to detect if it is still pressed down.

我知道“keydown”事件,但那不是我需要的。在按键被按下一段时间后,我希望能够检测到它是否仍然被按下。

P. S. The biggest issue seems to be that after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend. Hopefully there is just a simple isKeyDown(key) function, but if not then this issue will need to be overcome / worked around.

最大的问题似乎是经过一段时间后,钥匙开始重复,像一个恶魔一样触发按键和按键事件。希望只有一个简单的isKeyDown(key)函数,但是如果没有,那么这个问题就需要解决。

11 个解决方案

#1


51  

Is there a way to detect if a key is currently down in Javascript?

是否有一种方法可以检测一个键是否在Javascript中当前处于关闭状态?

Nope. The only possibility is monitoring each keyup and keydown and remembering.

不。唯一的可能就是监控每一个按键和按键并记住。

after some period of time the key begins to repeat, firing off keydown and keyup events like a fiend.

一段时间后,这个键开始重复,像一个恶魔一样触发按键和按键事件。

It shouldn't. You'll definitely get keypress repeating, and in many browsers you'll also get repeated keydown, but if keyup repeats, it's a bug.

这是不应该的。你肯定会得到按键重复,在许多浏览器中你也会得到重复按键,但是如果按键重复,那就是一个错误。

Unfortunately it is not a completely unheard-of bug: on Linux, Chromium, and Firefox (when it is being run under GTK+, which it is in popular distros such as Ubuntu) both generate repeating keyup-keypress-keydown sequences for held keys, which are impossible to distinguish from someone hammering the key really fast.

不幸的是,这并不是一个完全前所未闻的bug:在Linux、Chromium和Firefox(在GTK+下运行时,它在流行的发行版(比如Ubuntu)中运行)都为持有的密钥生成重复的按键按下键序列,这是不可能与某人快速敲击密钥区分的。

#2


99  

In addition to using keyup and keydown listeners to track when is key goes down and back up, there are actually some properties that tell you if certain keys are down.

除了使用keyup和keydown侦听器来跟踪什么时候键是向下和备份的,实际上还有一些属性告诉您某些键是否已经关闭。

window.Onmousemove= function (e) {
  if (!e) e = window.event;
  if (e.shiftKey) {/*shift is down*/}
  if (e.altKey) {/*alt is down*/}
  if (e.ctrlKey) {/*ctrl is down*/}
  if (e.metaKey) {/*cmd is down*/}
}

This are available on all browser generated event objects, such as those from keydown, keyup, and keypress, so you don't have to use mousemove.

这在所有浏览器生成的事件对象上都是可用的,比如keydown、keyup和keypress,所以您不必使用mousemove。

I tried generating my own event objects with document.createEvent('KeyboardEvent') and document.createEvent('KeyboardEvent') and looking for e.shiftKey and such, but I had no luck.

我尝试使用document.createEvent('KeyboardEvent')和document.createEvent('KeyboardEvent')生成我自己的事件对象,并查找e。轮班等等,但我没有运气。

I'm using Chrome 17 on Mac

我在Mac电脑上使用Chrome 17

#3


25  

My solution:

我的解决方案:

var keys = {};
window.Onkeyup= function(e) { keys[e.keyCode] = false; }
window.Onkeydown= function(e) { keys[e.keyCode] = true; }

I can now check if any key is pressed anywhere else in the script by checking

我现在可以通过检查来检查脚本中的其他地方是否按了键

keys["code of the key"]

If it's true, the key is pressed.

如果是真的,就按下键。

#4


10  

I don't believe there is anything like an isKeyDown function, but you could write your own.

我不相信有任何类似于isKeyDown函数的东西,但是您可以自己编写。

Basically, create an array whose length is the number of keys you want to monitor. Then using the documents/pages/controls keyUp and keyDown events, update the array with that key's state.

基本上,创建一个数组,它的长度是要监视的键的数量。然后使用document /pages/controls keyUp和keyDown事件,使用该键的状态更新数组。

Then write a function that checks if a certain key is down and returns a bool.

然后编写一个函数,检查某个键是否为down并返回bool。

var keyEnum = { W_Key:0, A_Key:1, S_Key:2, D_Key:3 };
var keyArray = new Array(4);

function onKeyDown()
{
    // Detect which key was pressed
    if( key == 'w' )
        keyArray[keyEnum.W_Key] = true;
    // Repeat for each key you care about...
}

function onKeyUp()
{
    // Detect which key was released
    if( key == 'w' )
        keyArray[keyEnum.W_Key] = false;
    // Repeat for each key you care about...
}

function isKeyDown(key)
{
    return keyArray[key];
}

That should accomplish what you want.

那应该实现你想要的。

#5


1  

Other people have asked this kind of question before (though I don't see any obvious dupes here right now).

其他人以前也问过这样的问题(尽管我现在没有看到任何明显的杜撰)。

I think the answer is that the keydown event (and its twin keyup) are all the info you get. Repeating is wired pretty firmly into the operating system, and an application program doesn't get much of an opportunity to query the BIOS for the actual state of the key.

我认为答案是keydown事件(以及它的双关键字)是你得到的所有信息。重复非常牢固地连接到操作系统中,而应用程序没有太多机会查询BIOS中键的实际状态。

What you can do, and perhaps have to if you need to get this working, is to programmatically de-bounce the key. Essentially, you can evaluate keydown and keyup yourself but ignore a keyupevent if it takes place too quickly after the last keydown... or essentially, you should delay your response to keyup long enough to be sure there's not another keydown event following with something like 0.25 seconds of the keyup.

您可以做的,如果您需要让这个工作,那么可能必须做的就是以编程方式反弹键。本质上,您可以自己评估keydown和keyup,但如果keyupevent在最后一个keydown之后发生得太快,您可以忽略它……或者从本质上说,您应该将对keyup的响应延迟足够长的时间,以确保不会有另一个keydown事件以类似于0.25秒的keyup的方式发生。

This would involve using a timer activity, and recording the millisecond times for previous events. I can't say it's a very appealing solution, but...

这将涉及使用一个计时器活动,并为以前的事件记录毫秒数。我不能说这是一个很吸引人的解决方案,但是……

#6


1  

/*
Tracks what keys are currently down on the keyboard
*/

function keyboard_module(onUpdate){
    var kb = {};
    var unicode_mapping = {};
    document.Onkeydown= function(e){
        var unicode=e.charCode? e.charCode : e.keyCode
        var key = getKey(unicode);
        kb[key] = true;
        if(onUpdate){
            onUpdate(kb);
        }
    }

    document.Onkeyup= function(e){
        var unicode=e.charCode? e.charCode : e.keyCode
        var key = getKey(unicode);
        delete kb[key];
        if(onUpdate){
            onUpdate(kb);
        }
    }

    function getKey(unicode){
        if(unicode_mapping[unicode]){
            var key = unicode_mapping[unicode];
        }else{
            var key= unicode_mapping[unicode] = String.fromCharCode(unicode);
        }
        return key;
    }
    return kb;
}

function testing(kb){
    console.log('These are the down keys', kb);
}


var keyboard = keyboard_module(testing);

....
//somewhere else in the code
if(keyboard['K']){/*do something special */}

#7


1  

The following code is what I'm using:

下面的代码是我正在使用的:

var altKeyDownCount = 0;
window.Onkeydown= function (e) {
    if (!e) e = window.event;
    if (e.altKey) {
        altKeyDownCount++;
        if (30 

When the user keeps holding down the Alt key for some time (about 2 seconds), a group of labels (class='key hidden') appears. When the Alt key is released, the labels disappear. jQuery and Bootstrap are both used.

当用户按住Alt键一段时间(大约2秒)时,会出现一组标签(class='key hidden')。当Alt键被释放时,标签就会消失。jQuery和Bootstrap都使用过。

#8


0  

Look at this answer, and use onkeyup and onkeydown. Here is more specific info about those events.

看看这个答案,使用onkeyup和onkeydown。这里有关于这些事件的更具体的信息。

#9


0  

I know this is very old question, however there is a very lightweight (~.5Kb) Javascript library that effectively "patches" the inconsistent firing of keyboard event handlers when using the DOM API.

我知道这是一个非常古老的问题,但是有一个非常轻量级(~. 5kb)的Javascript库,它在使用DOM API时有效地“修补”了键盘事件处理程序不一致的触发。

The library is Keydrown.

图书馆是Keydrown。

Here's the operative code sample that has worked well for my purposes by just changing the key on which to set the listener:

这里有一个运行良好的代码示例,它通过改变设置监听器的键来达到我的目的:

kd.P.down(function () {
  console.log('The "P" key is being held down!');
});

kd.P.up(function () {
  console.clear();
});

// This update loop is the heartbeat of Keydrown
kd.run(function () {
  kd.tick();
});

I've incorporated Keydrown into my client-side Javascript for a proper pause animation in a Red Light Green Light game I'm writing. You can view the entire game here. (Note: If you're reading this in the future, the game should be code complete and playable :-D!)

在我正在编写的一个红绿灯游戏中,我将key溺死在我的客户端Javascript中,以获得一个适当的暂停动画。你可以在这里看到整个游戏。(注意:如果你将来要读这篇文章,游戏应该是完整的代码并且可以玩:-D!)

I hope this helps.

我希望这可以帮助。

#10


0  

Ended up here to check if there was something builtin to the browser already, but it seems there isn't. This is my solution (very similar to Robert's answer):

最后在这里检查浏览器是否已经内置了一些东西,但似乎没有。这是我的解决方案(非常类似于罗伯特的答案):

"use strict";

let is_key_down = (() => {
    let state = {};

    window.addEventListener('keyup', (e) => state[e.key] = false);
    window.addEventListener('keydown', (e) => state[e.key] = true);

    return (key) => state.hasOwnProperty(key) && state[key] || false;
})();

You can then check if a key is pressed with is_key_down('ArrowLeft').

然后,您可以使用is_key_down(“ArrowLeft”)检查是否按了键。

#11


-2  

$('#mytextbox').keydown(function (e) {
            if (e.keyCode == 13) {
                if (e.altKey) {
                    alert("alt is pressed");
                }
            }
 });

if you press alt + enter, you will see the alert.

如果你按alt + enter,你会看到警报。


推荐阅读
  • 本文深入探讨了UNIX/Linux系统中的进程间通信(IPC)机制,包括消息传递、同步和共享内存等。详细介绍了管道(Pipe)、有名管道(FIFO)、Posix和System V消息队列、互斥锁与条件变量、读写锁、信号量以及共享内存的使用方法和应用场景。 ... [详细]
  • 主调|大侠_重温C++ ... [详细]
  • 本文详细探讨了Java中的ClassLoader类加载器的工作原理,包括其如何将class文件加载至JVM中,以及JVM启动时的动态加载策略。文章还介绍了JVM内置的三种类加载器及其工作方式,并解释了类加载器的继承关系和双亲委托机制。 ... [详细]
  • 本文探讨了如何使用pg-promise库在PostgreSQL中高效地批量插入多条记录,包括通过事务和单一查询两种方法。 ... [详细]
  • 本文详细探讨了使用纯JavaScript开发经典贪吃蛇游戏的技术细节和实现方法。通过具体的代码示例,深入解析了游戏逻辑、动画效果及用户交互的实现过程,为开发者提供了宝贵的参考和实践经验。 ... [详细]
  • 配置PHPStudy环境并使用DVWA进行Web安全测试
    本文详细介绍了如何在PHPStudy环境下配置DVWA( Damn Vulnerable Web Application ),并利用该平台进行SQL注入和XSS攻击的练习。通过此过程,读者可以熟悉常见的Web漏洞及其利用方法。 ... [详细]
  • 软件工程课堂测试2
    要做一个简单的保存网页界面,首先用jsp写出保存界面,本次界面比较简单,首先是三个提示语,后面是三个输入框,然 ... [详细]
  • 本文旨在探讨如何利用决策树算法实现对男女性别的分类。通过引入信息熵和信息增益的概念,结合具体的数据集,详细介绍了决策树的构建过程,并展示了其在实际应用中的效果。 ... [详细]
  • 序列化与反序列化是数据处理中的重要技术,特别是在网络通信和数据存储中。它们允许将复杂的数据结构转换为可传输或存储的格式,再从这些格式恢复原始数据。本文探讨了序列化与反序列化的基本概念,以及它们在不同协议模型中的角色。 ... [详细]
  • 使用WinForms 实现 RabbitMQ RPC 示例
    本文通过两个WinForms应用程序演示了如何使用RabbitMQ实现远程过程调用(RPC)。一个应用作为客户端发送请求,另一个应用作为服务端处理请求并返回响应。 ... [详细]
  • 本文介绍了一种根据目标检测结果,从原始XML文件中提取并分析特定类别的方法。通过解析XML文件,筛选出特定类别的图像和标注信息,并保存到新的文件夹中,以便进一步分析和处理。 ... [详细]
  • cJinja:C++编写的轻量级HTML模板引擎
    本文介绍了cJinja,这是一个用C++编写的轻量级HTML模板解析库。它利用ejson来处理模板中的数据替换(即上下文),其语法与Django Jinja非常相似,功能强大且易于学习。 ... [详细]
  • 本文详细探讨了在微服务架构中,使用Feign进行远程调用时出现的请求头丢失问题,并提供了具体的解决方案。重点讨论了单线程和异步调用两种场景下的处理方法。 ... [详细]
  • 本文介绍如何在Laravel框架中集成微信支付功能,包括如何配置微信支付环境、处理支付请求及接收支付回调等关键步骤。 ... [详细]
  • 在处理木偶评估函数时,我发现可以顺利传递本机对象(如字符串、列表和数字),但每当尝试将JSHandle或ElementHandle作为参数传递时,函数会拒绝接受这些对象。这可能是由于这些句柄对象的特殊性质导致的,建议在使用时进行适当的转换或封装,以确保函数能够正确处理。 ... [详细]
author-avatar
许琼博762375
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有