什么是背后的jQuery keypress,keydown,keyup黑魔法(在Macs)的理论?

前端之家收集整理的这篇文章主要介绍了什么是背后的jQuery keypress,keydown,keyup黑魔法(在Macs)的理论?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对keypress,keydown和keyup的各种行为感到困惑。看来我错过了一个重要的文档,解释这三个细节的微妙和细微差别。有人可以帮助我找出哪个文档,我需要阅读,以便更有效地使用这些事件?如果你想要详细信息,请参见下面。

@ o.v .:你要求我展示一些代码,但它并不是我试图解决代码中的一个具体问题。我试图得到一个处理这些事件处理程序的行为,并要求某人理解他们指向我一个很好的文档。

我使用jQuery构建一个输入表单并将其插入我的文档。它的工作很好,大多数。我想要窗体响应键盘像我看到的大多数其他输入形式:esc键应该关闭窗体与单击取消按钮相同,并且因为窗体有一个< textarea>对它,cmd输入应该与单击确定按钮相同。看起来很简单,使用keypress事件。问题是Chrome不会调用Esc键或cmd回车的keypress处理程序。它触发ctrl输入和选项输入和字母数字,但不是cmd输入。

所以我将使用keyup代替。我得到keyup为esc,keyup为cmd,keyup为enter,伟大的。但我没有得到keyup输入键,而我按住cmd。

第三次的魅力,你可能会想。 keydown似乎工作,但与keydown,你得到重复键。我知道,你所要做的就是在第一次调用时解除绑定处理程序,但是似乎很奇怪,三种不同的事件类型会有不同的行为。为什么是这样?有没有明显的文件,我明显没有阅读?

解决方法

Keypress

The keypress event is sent to an element when the browser registers
keyboard input. This is similar to the keydown event,except in the
case of key repeats
. If the user presses and holds a key,a keydown
event is triggered once,but separate keypress events are triggered
for each inserted character
. In addition,modifier keys (such as
Shift) trigger keydown events but not keypress events.

Keydown

The keydown event is sent to an element when the user first presses a
key on the keyboard
. It can be attached to any element,but the event
is only sent to the element that has the focus. Focusable elements can
vary between browsers,but form elements can always get focus so are
reasonable candidates for this event type.

Keyup

The keyup event is sent to an element when the user releases a key on
the keyboard
. It can be attached to any element,but the event is only
sent to the element that has the focus. Focusable elements can vary
between browsers,but form elements can always get focus so are
reasonable candidates for this event type.

此外,这是一个方便的信息,通常被掩盖:

If key presses anywhere need to be caught (for example,to implement
global shortcut keys on a page),it is useful to attach this behavior
to the document object. Because of event bubbling,all key presses
will make their way up the DOM to the document object unless
explicitly stopped.

To determine which character was entered,examine the event object
that is passed to the handler function. While browsers use differing
properties to store this information
,jQuery normalizes the .which
property so you can reliably use it to retrieve the character code.

Note that keydown and keyup provide a code indicating which key is
pressed,while keypress indicates which character was entered.
For
example,a lowercase “a” will be reported as 65 by keydown and keyup,
but as 97 by keypress. An uppercase “A” is reported as 65 by all
events. Because of this distinction,when catching special keystrokes
such as arrow keys,.keydown() or .keyup() is a better choice.

有关MACs上的cmd键的更多信息:jQuery key code for command key

原文链接:https://www.f2er.com/jquery/185340.html

猜你在找的jQuery相关文章