开发者

javascript textarea: what was typed/pasted, and where?

How do you find out what the user typed or pasted into a textarea? For example, if they typed in B (or β) at index 1, or if they pasted hello world\n at index 23. I've searched a fair bit but can't find anything. Here's what I have so far, uses jQuery:

$("textarea").keydown(function(evt){
    var index= getCaret(this); // this.selectionStart doesn't work in IE
    var key = evt.keyCo开发者_如何学Cde; // Wrong.
}

See this question for getCaret. The problem with event.keyCode is non-english keyboard layouts. I'm entirely stuck as far pasting is concerned.

If possible, I'd like to know the values before the textarea is changed - that is, from within the keydown event. I'm not sure if this can be done for pasting.

(Deletion is easier - detect keyCode==8 for backspace and keyCode==46 for del. If selection.length > 0, then the selection is removed; otherwise the character before or after is removed. In theory. There's also the case of pasting on top of a selection.)

Anything that gets any part of this closer to working in any browser is greatly appreciated. That is, how do you know:

  1. the unicode string value of the typed character?
  2. when a paste occurred?
  3. what the text content of the paste is?


I'm not quite sure what your ultimate goal is here, so it's difficult to advise. However, here's some information:

When the user types a character, getting what they typed is easy enough using the keypress event and (assuming your event object is stored in a a variable called evt) using String.fromCharCode(evt.keyCode || evt.which).

For pasting, things are a bit trickier. The simplest thing would be to detect the paste before it has happened, store the textarea's value and after a very short time (using window.setTimeout) compare the new value with the old. As for detecting the paste, a lot of browsers now have the paste event: IE since version 5, Firefox since version 3 and WebKit browsers for a while (not sure exactly when), so you can use that for those browsers. As a fallback for other browsers you could detect Ctrl-V and Shift-Insert in a keydown event handler, though this is by no means foolproof since it won't fire when the user pastes using the Edit menu or the context menu in their browser.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜