您的位置:首页 > Web前端 > JQuery

js/jquery 实时监听输入框值变化的完美方案:oninput & onpropertychange

2016-06-13 16:28 826 查看
(1)先说jquery,使用jQuery库的话,只需要同时绑定oninput和onpropertychange两个事件就可以了,示例代码:

$('#username').bind('inputpropertychange',function(){ $('#content').html($(this).val().length+'characters'); });

  



(2)对于JS原生写法而言,oninput是HTML5的标准事件,对于检测textarea,input:text,input:password和input:search这几个元素通过用户界面发生的内容变化非常有用,在内容修改后立即被触发,不像onchange事件需要失去焦点才触发。oninput事件在主流浏览器的兼容情况如下:

  


  从上面表格可以看出,oninput事件在IE9以下版本不支持,需要使用IE特有的onpropertychange事件替代,这个事件在用户界面改变或者使用脚本直接修改内容两种情况下都会触发,有以下几种情况:

修改了input:checkbox或者input:radio元素的选择中状态,checked属性发生变化。

修改了input:text或者textarea元素的值,value属性发生变化。

修改了select元素的选中项,selectedIndex属性发生变化。

  在监听到onpropertychange事件后,可以使用event的propertyName属性来获取发生变化的属性名称。

  集合oninput&onpropertychange监听输入框内容变化的示例代码如下:

<head>
<scripttype="text/javascript">
//Firefox,GoogleChrome,Opera,Safari,InternetExplorerfromversion9
functionOnInput(event){
alert("Thenewcontent:"+event.target.value);
}
//InternetExplorer
functionOnPropChanged(event){
if(event.propertyName.toLowerCase()=="value"){
alert("Thenewcontent:"+event.srcElement.value);
}
}
</script>
</head>
<body>
Pleasemodifythecontentsofthetextfield.
<inputtype="text"oninput="OnInput(event)"onpropertychange="OnPropChanged(event)"
value="Textfield"/>
</body>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: