数码资讯
即时反应的input和propertychange方法
在web开发中,我们有时会需要动态监听输入框值的变化,当使用onkeydown、onkeypress、onkeyup作为监听事件时,会发现一些复制粘贴等操作用不了,同时,在处理组合快键键的时候也很麻烦。这时候我们需要更专业的解决方案:HTML5标准事件oninput、onchange和IE专属的事件properchange。
1.oninput&onchange:
oninput和onchange都是事件对象,当输入框的值发生改变时触发该事件。不同的是,oninput是在值改变时立即触发,而onchange是在值改变后失去焦点才触发,并且可以用在非输入框中,如:select等。
2.propertychange:
功能同oninput,用以替代oninput在IE9以下的不兼容性。
3.output:
output是一个HTML5标签,IE系列浏览不兼容,主要用于计算输出。如:
propertychange 和 input 事件:
1)propertychange只要当前对象的属性发生改变就会触发该事件
2)input是标准的浏览器事件,一般应用于input元素,当input的value发生变化就会发生,无论是键盘输入还是鼠标黏贴的改变都能及时监听到变化
$(function(){
$(‘#username‘).bind(‘input propertychange‘, function() {
$(‘#result‘).html($(this).val().length + ‘ characters‘);
});
})
这里bind同时绑定了input和propertychange两个方法。
转:http://www.codes51.com/article/detail_3922282.html
在 Web 开发中经常会碰到需要动态监听输入框值变化的情况,如果使用 onkeydown、onkeypress、onkeyup 这个几个键盘事件来监测的话,监听不了右键的复制、剪贴和粘贴这些操作,处理组合快捷键也很麻烦。因此这篇文章向大家介绍一种完美的解决方案:结合 HTML5 标准事件 oninput 和 IE 专属事件 onpropertychange 事件来监听输入框值变化。
您可能感兴趣的相关文章
- 60款非常精美的 jQuery 幻灯片演示和下载
- 精心挑选的优秀jQuery Ajax分页插件和教程
- 推荐几款非常棒的 jQuery 全景图片展示插件
- 精心挑选的优秀 jQuery 文本特效插件和教程
- 精心挑选的美轮美奂的 jQuery 图片特效插件
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 监听输入框内容变化的示例代码如下:
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/):