oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素经过用户界面发生的内容变化很是有用,在内容修改后当即被触发,不像 onchange 事件须要失去焦点才触发。oninput 事件在主流浏览器的兼容状况以下:javascript
从上面表格能够看出,oninput 事件在 IE9 如下版本不支持,须要使用 IE 特有的 onpropertychange 事件替代,这个事件在用户界面改变或者使用脚本直接修改内容两种状况下都会触发,有如下几种状况:php
在监听到 onpropertychange 事件后,能够使用 event 的 propertyName 属性来获取发生变化的属性名称。html
集合 oninput & onpropertychange 监听输入框内容变化的示例代码以下:html5
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
<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 两个事件就能够了,示例代码以下:java
1
2
3
|
$(
'textarea'
).bind(
'input propertychange'
,
function
() {
$(
'.msg'
).html($(
this
).val().length +
' characters'
);
});
|
下面是 JsFiddle 在线演示,若是不能显示请刷新一下页面或者点击后面的连接(http://jsfiddle.net/PVpZf/): 浏览器
最后须要注意的是:oninput 和 onpropertychange 这两个事件在 IE9 中都有个小BUG,那就是经过右键菜单菜单中的剪切和删除命令删除内容的时候不会触发,而 IE 其余版本都是正常的,目前尚未很好的解决方案。不过 oninput & onpropertychange 仍然是监听输入框值变化的最佳方案,若是你们有更好的方法,欢迎参与讨论。this
参考资料:spa