oninput事件是html5的标准事件,支持ie9和以上以及其他的火狐啊谷歌啊等浏览器
ie9以下的可以用onpropertychange
<head>
<script type="text/javascript">
// Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9
function OnInput (event) {
alert ("The new content: " + event.target.value);
}
// Internet Explorer
function OnPropChanged (event) {
if (event.propertyName.toLowerCase () == "value") {
alert ("The new content: " + event.srcElement.value);
}
}
</script>
</head>
<body>
Please modify the contents of the text field.
<input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />
</body>
使用 jQuery 库的话,只需要同时绑定 oninput 和 onpropertychange 两个事件就可以了,示例代码如下:
$('textarea').bind('input propertychange', function() {
$('.msg').html($(this).val().length + ' characters');
});
最后需要注意的是:oninput 和 onpropertychange 这两个事件在 IE9 中都有个小BUG,那就是通过右键菜单菜单中的剪切和删除命令删除内容的时候不会触发,而 IE 其他版本都是正常的,目前还没有很好的解决方案。不过 oninput & onpropertychange 仍然是监听输入框值变化的最佳方案,如果大家有更好的方法,欢迎参与讨论。
破罐子互摔