3

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!

4

3 に答える 3

6

クロスブラウザソリューションを探しているなら、あなたは大変な時間を過ごすだろうと思います。ここにあなたを助けるための何かがあります:http ://www.quirksmode.org/dom/events/keys.html

基本的に、次のようなものが必要です。

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

イベントのMDN。おそらくもっと役立つ

于 2012-07-16T19:36:18.863 に答える
5
var textarea = document.getElementById('textarea');

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

jQuery の使用 (デリゲート)。

$("body").delegate("textarea", "keydown",function(e){
        alert("Test");
        //code logic goes here
        //if(e.which == 13){
        //Enter key down    
    }
});

または

$('textarea').live("keydown", function(e) {
    alert("Test");
    // e.which is which key, e.g. 13 == enter
});

ライブのドキュメント。イベントに関するドキュメント。

于 2012-07-16T19:40:45.447 に答える