How to use keydown event in textarea?

不想你离开。 提交于 2019-12-06 10:34:23

问题


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.

I have already written a function that inserts the text at the text cursor insertAtCursor(text). The ID of the textarea is "content".

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!


回答1:


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

Basically, you'd want something like this:

document.getElementById('content').addEventListener('keydown', function (e){
    // Do your key combination detection
}, false);

MDN on events. Probably more helpful




回答2:


var textarea = document.getElementById('textarea');

textarea.onkeydown = function ()
{
   alert("Test");
};

Using jQuery (delegate).

$("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
});

Docs on live. Docs on event.



来源:https://stackoverflow.com/questions/11511250/how-to-use-keydown-event-in-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!