oninput 是 HTML5 的标准事件,对于检测 textarea, input:text, input:password 和 input:search 这几个元素经过用户界面发生的内容变化很是有用,在内容修改后当即被触发,不像 onchange 事件须要失去焦点才触发。oninput 事件在主流浏览器的兼容状况以下:javascript
从上面表格能够看出,oninput 事件在 IE9 如下版本不支持,须要使用 IE 特有的 onpropertychange 事件替代,这个事件在用户界面改变或者使用脚本直接修改内容两种状况下都会触发,有如下几种状况:html
在监听到 onpropertychange 事件后,可使用 event 的 propertyName 属性来获取发生变化的属性名称。java
集合 oninput & onpropertychange 监听输入框内容变化的示例代码以下:jquery
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 两个事件就能够了,示例代码以下:浏览器
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 仍然是监听输入框值变化的最佳方案post
遇到如此需求,首先想到的是change事件,但用过change的都知道只有在input失去焦点时才会触发,并不能知足实时监测的需求,好比监测用户输入字符数。this
在通过查阅一番资料后,欣慰的发现firefox等现代浏览器的input有oninput这一属性,能够用三种方式使用它:url
1,内嵌元素方式(属性编辑方式)spa
<input id="test" oninput="console.log('input');" type="text" />
2,句柄编辑方式
document.getElementById('test').oninput=function(){ console.log('input'); }
3,事件侦听方式(jquery)
$('#test').on('input',function(){
console.log('input');
})
可是,以上代码仅在除了ie的浏览器大大们里才work,那ie该怎么处理呢? 在ie中有一个属性叫作onpropertychange:
<input id="test" onpropertychange="alert('change');" type="text" />
通过调试后立刻就会发现,这个属性是在元素的任何属性变化时都会起做用,包括咱们这里所提到的value,但至少是起做用了,那接下来的任务就是筛选出property为value的变化。
document.getElementById('test').attachEvent('onpropertychange',function(e) { if(e.propertyName!='value') return; $(that).trigger('input'); });
在上面代码中的回调函数中会传入一个参数,为该事件,该事件有不少属性值,搜寻一下能够发现有一个咱们很关心的,叫作propertyName,也就是当前发生变化的属性名称。而后就至关简单了,只要在回调函数中判断一下是否为咱们所要的value,是的话就trigger一下‘input’事件。
而后,就能够在主流浏览器中统一用这样的方式来监听‘input’事件了。
$('#test').on('input',function(){ alert('input'); })
最后贴上完整代码:
$('#test').on('input',function(){ alert('input'); }) //for ie if(document.all){ $('input[type="text"]').each(function() { var that=this; if(this.attachEvent) { this.attachEvent('onpropertychange',function(e) { if(e.propertyName!='value') return; $(that).trigger('input'); }); } }) }
转自:http://www.cnblogs.com/lhb25/archive/2012/11/30/oninput-and-onpropertychange-event-for-input.html
http://www.cnblogs.com/asie-huang/archive/2012/07/10/2585038.html