The best way to do this, cross-browser: use a combination of the input
and onpropertychange
events, like so:
var area = container.querySelector('textarea');
if (area.addEventListener) {
area.addEventListener('input', function() {
// event handling code for sane browsers
}, false);
} else if (area.attachEvent) {
area.attachEvent('onpropertychange', function() {
// IE-specific event handling code
});
}
The input
event takes care of IE9+, FF, Chrome, Opera and Safari, and onpropertychange
takes care of IE8 (it also works with IE6 and 7, but there are some bugs).
The advantage of using input
and onpropertychange
is that they don't fire unnecessarily (like when pressing the Ctrl
or Shift
keys); so if you wish to run a relatively expensive operation when the textarea contents change, this is the way to go.
Now IE, as always, does a half-assed job of supporting this: neither input
nor onpropertychange
fires in IE when characters are deleted from the textarea. So if you need to handle deletion of characters in IE, use keypress
(as opposed to using keyup
/ keydown
, because they fire only once even if the user presses and holds a key down).
Source: http://www.alistapart.com/articles/expanding-text-areas-made-elegant/
EDIT: It seems even the above solution is not perfect, as rightly pointed out in the comments: the presence of the addEventListener
property on the textarea does not imply you're working with a sane browser; similarly the presence of the attachEvent
property does not imply IE. If you want your code to be really air-tight, you should consider changing that. See Tim Down's comment for pointers.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…