将 keydown 传递给另一个元素
我想将 keydown 事件传递给另一个元素。一路上我发现 :
$('input').keydown(function(e) {
$('textarea').keydown()[0].focus();
});
有效,而 :
$('input').keydown(function(e) {
setTimeout(function() { $('textarea').keydown()[0].focus(); }, 0);
});
不起作用。至少在 Chrome 中是这样。
无论如何,我想用第二种方法来做到这一点,因为我希望它首先能够在选择了文本的输入上执行 ctrl+c
或 ctrl+x
,然后跳转到文本区域。
这里有一个 DEMO 可以看看我的意思。
为什么第二种方法不起作用?还有什么办法可以实现这一点吗?
I want to pass a keydown event to another element. Along the way I found that :
$('input').keydown(function(e) {
$('textarea').keydown()[0].focus();
});
works and that:
$('input').keydown(function(e) {
setTimeout(function() { $('textarea').keydown()[0].focus(); }, 0);
});
doesn't work. At least in Chrome.
Anyway I want to do this with the second method as I want it to first be able to do a ctrl+c
or ctrl+x
on an input that has text selected and then jump to the textarea.
Here's a DEMO to see what I mean.
Why doesn't the second way work? Also is there any way to accomplish this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
按预期工作。首先,你的代码有一半是不相关的。 :p
相当于
,它在 keyhandler 解析之前将焦点转移到
textarea
。密钥最终位于textarea
中。input
甚至看不到它。 (假设代码显示的是input
而不是inout
)。第二个例子:
相当于:
所以,由于超时,首先
keydown
事件完成,按键被接受为input
的输入,然后是延迟函数被调用并改变焦点。没有进一步的事情发生。我不知道如何“重复”或“重新抛出”键盘事件,以防您想在
input
和textarea
中获得相同的按键(如果是这样的话)你想要什么;我不是 100% 确定你想要什么)。编辑:好的:如果只是 Ctrl/Shift/另一个修饰键,则返回 true,以便默认处理程序选择它。如果是 Ctrl-C(即设置了
ctrlKey
的C
键(Mac 上的metaKey
),则执行超时操作(因此input
在focus
之前捕获它);如果没有,则立即移动焦点(因此textarea
捕获它)。目前比较好的方法。Works as expected. First of all, half of your code is irrelevant. :p
is equivalent to
and it transfers the focus to the
textarea
before the keyhandler resolves. The key ends up in thetextarea
. and theinput
doesn't even see it. (assume the code saysinput
and notinout
).The second example:
is equivalent to:
so, because of the timeout, first the
keydown
event completes, the key is accepted as input to theinput
, and then the delayed function gets invoked and changes focus. Nothing further happens.I don't know how to "repeat" or "rethrow" a keyboard event, in case you want to get the same keypress in both
input
andtextarea
(if that's what you wanted; I am not 100% sure what you wanted).EDIT: Okay: if it's just Ctrl/Shift/another modifier key, return true so the default handler picks it up. If it's Ctrl-C (i.e.
C
key withctrlKey
set (metaKey
on Mac), do the timeout thing (so theinput
catches it before thefocus
); if not, move focus immediately (so thetextarea
catches it). Not trivial, and I can't think of a better method at the moment.为
setTimeout
传递足够的时间,延迟textarea
上的keydown
事件没有任何意义,可以删除;Pass enough time for the
setTimeout
delaythe
keydown
event on thetextarea
has no sense, and can be removed;