监听输入框变化(oninput,onpropertychange,onchange)

it2022-05-05  103

oninput,onpropertychange,onchange: oninput是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器,但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。 onpropertychange的话,只要当前对象属性发生改变,都会触发事件,但是它是IE专属的; onchange触发事件必须满足两个条件: a)当前对象属性改变,并且是由键盘或鼠标事件激发的(脚本触发无效) b)当前对象失去焦点(onblur); 注意:oninput和  onpropertychange这两个事件在 IE9 中都有个小BUG,那就是通过右键菜单菜单中的剪切和删除命令删除内容的时候不会触发  

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

 javascript写法:

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

<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写法(需要引入jquery库):

<script> $('textarea').bind('input propertychange', function() { $('.msg').html($(this).val().length + ' characters'); }); </script>

 

  

 

     

转载于:https://www.cnblogs.com/wteng/p/5434403.html


最新回复(0)