我想将 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
选中文本,然后跳转到文本区域。
Here's a DEMO to see what I mean.
为什么第二种方式行不通?还有什么办法可以做到这一点?
最佳答案
按预期工作。首先,你的一半代码是无关紧要的。 :p
$('inout').keydown(function(e) {
$('textarea').keydown()[0].focus();
});
相当于
$('inout').keydown(function(e) {
$('textarea').keydown(); // doesn't do anything sensible
$('textarea')[0].focus();
});
并在键处理程序解析之前将焦点转移到 textarea
。 key 最终出现在 textarea
中。而 input
甚至看不到它。 (假设代码说的是 input
而不是 inout
)。
第二个例子:
$('input').keydown(function(e) {
setTimeout(function() { $('textarea').keydown()[0].focus(); }, 0);
});
相当于:
$('input').keydown(function(e) {
setTimeout(function() {
$('textarea').keydown(); // doesn't do anything sensible
$('textarea')[0].focus();
}, 0);
});
因此,由于超时,首先 keydown
事件完成,键被接受为 input
的输入,然后延迟函数被调用并改变焦点.没有进一步的事情发生。
如果您想在 input
和 textarea
中获得相同的按键,我不知道如何“重复”或“重新抛出”键盘事件(如果那是你想要的;我不是 100% 确定你想要什么)。
编辑:好的:如果只是 Ctrl/Shift/另一个修饰键,则返回 true,以便默认处理程序选择它。如果是 Ctrl-C(即设置了 ctrlKey
的 C
键(在 Mac 上为 metaKey
),请执行超时操作(因此 input
在 focus
之前捕获它);如果没有,立即移动焦点(因此 textarea
捕获它)。这不是微不足道的,我想不出目前更好的方法。
关于javascript - 将 keydown 传递给另一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9317249/