javascript 如何在textarea中使用keydown事件?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11511250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use keydown event in textarea?
提问by DoubleTrouble
I am not very used to using javascript but I have gotten sick of manually repeating a tast at work. When I write in a discussion forum I need a quick short command, like Ctrl-Alt-z, to insert some text into a textarea object.
我不太习惯使用 javascript,但我已经厌倦了在工作中手动重复测试。当我在论坛上写作时,我需要一个快速的简短命令,例如 Ctrl-Alt-z,将一些文本插入到 textarea 对象中。
I have already written a function that inserts the text at the text cursor insertAtCursor(text). The ID of the textarea is "content".
我已经编写了一个在文本光标 insertAtCursor(text) 处插入文本的函数。文本区域的 ID 是“内容”。
I know how to solve the problem of checking for key combinations. The problem I have is basically to check for any keyboard input at all.
我知道如何解决检查组合键的问题。我遇到的问题基本上是检查是否有任何键盘输入。
I have tried the following:
我尝试了以下方法:
document.keydown(function(event){
alert("Test");
});
However, it does not work.
但是,它不起作用。
Thanks in advance!
提前致谢!
回答by Some Guy
I think you're going to have a tough time if you're looking for cross-browser solutions. Here's something to help you: http://www.quirksmode.org/dom/events/keys.html
如果您正在寻找跨浏览器的解决方案,我认为您将遇到困难。这里有一些可以帮助你的东西:http: //www.quirksmode.org/dom/events/keys.html
Basically, you'd want something like this:
基本上,你会想要这样的东西:
document.getElementById('content').addEventListener('keydown', function (e){
// Do your key combination detection
}, false);
回答by Lion
var textarea = document.getElementById('textarea');
textarea.onkeydown = function ()
{
alert("Test");
};
Using jQuery (delegate).
使用 jQuery(委托)。
$("body").delegate("textarea", "keydown",function(e){
alert("Test");
//code logic goes here
//if(e.which == 13){
//Enter key down
}
});
Or
或者
$('textarea').live("keydown", function(e) {
alert("Test");
// e.which is which key, e.g. 13 == enter
});