简体   繁体   English

在客户端 JavaScript 中,是否可以捕获事件并在稍后阶段触发它?

[英]In client-side JavaScript, is it possible to capture an event and fire it at a later stage?

I'm interested in doing something like this:我有兴趣做这样的事情:

...
event.preventDefault();
...
el.dispatchEvent(event);

I tried this in Firefox, which threw an NS_ERROR_ILLEGAL_VALUE exception.我在 Firefox 中试过这个,它抛出了一个NS_ERROR_ILLEGAL_VALUE异常。

Is it possible to capture an event and fire it at a later stage?是否可以捕获事件并在稍后阶段触发它?


For those that are interested, here's my high-level objective.对于那些感兴趣的人,这是我的高级目标。 I'm trying to determine when an underscore is typed into a textarea (ie shift + - ).我正在尝试确定何时将下划线输入到 textarea 中(即shift + - )。 Unfortunately, Firefox reports the keyCode and charCode for this event are 0, the same value given to the tilde ( shift + ` ) keystroke.不幸的是,Firefox 报告此事件的keyCodecharCode为 0,与波浪号 ( shift + ` ) 击键的值相同。 To disambiguate, my idea is to capture the event, suppress its default behaviour, and "release" it on another textarea.为了消除歧义,我的想法是捕获事件,抑制其默认行为,并将其“释放”到另一个文本区域。 I'd then inspect the value of this (hidden) textarea to determine which key was pressed.然后我会检查这个(隐藏的)文本区域的值以确定按下了哪个键。

Update: I'm using onkeydown , not onkeypress .更新:我使用的是onkeydown ,而不是onkeypress

As far as I know, an event already in the queue cannot be "reused" because it cannot be "pulled out" of the queue.据我所知,已经在队列中的事件不能被“重用”,因为它不能被“拉出”队列。 It's given to you, then to the next handler in line, and so on, but the native delegate is the same for all of them.它先给你,然后给下一个处理程序,依此类推,但本机委托对所有这些都是相同的。 So, you have to make a new one.所以,你必须做一个新的。 Since you're saying you can't get all the data about the event out, that's a problem.既然您说您无法获取有关该事件的所有数据,那就是个问题。

An easier trick may be to watch the textarea for change, and then delete the underscore when it appears in the text.一个更简单的技巧可能是观察 textarea 的变化,然后在下划线出现在文本中时将其删除。 If you want to maintain the cursor position, you can look here for a solution on how to exactly position the cursor (RonPK's response).如果要保持光标位置,可以在此处查找有关如何准确定位光标的解决方案(RonPK 的响应)。

Out of curiosity, according to my test here , Firefox 4 reports the correct charCode and shift state.出于好奇,根据我在这里的测试,Firefox 4 报告了正确的 charCode 和 shift 状态。 Is this a specific version/OS issue?这是特定版本/操作系统问题吗?

What's wrong with:有什么问题:

String.fromCharCode(event.keyCode);

? ?

Eg within the event handler:例如在事件处理程序中:

var character = String.fromCharCode(event.keyCode);
if (character === '_') {
    // Do something.
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM