Js/jQuery实时监听input输入框值变化

淡淡的烟草味﹌ 2021-09-14 14:32 510阅读 0赞

前言

在做web开发时候很多时候都需要即时监听输入框值的变化,以便作出即时动作去引导浏览者增强网站的用户体验感。而采用onchange时间又往往是在输入框失去焦点(onblur)时候触发,有时候并不能满足条件。

首先看一下dom中元素事件:

  • onpropertychange: IE下,当一个HTML元素的属性改变的时候,都能通过 onpropertychange来即时捕获。onchange在属性值改变时还必须使得当前元素失去焦点(onblur)才可以激活该事件。 在用js脚本改动该元素值时候亦能触发onpropertychange事件。
  • oninput:是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器,但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。
  • onchange: (a)当前对象属性改变,并且是由键盘或鼠标事件激发的(脚本触发无效);(b)当前对象失去焦点(onblur);

jQuery用法

  1. $("#input1").bind("input propertychange",function(event){
  2. console.log($("#input1").val())
  3. });

原生Js

  1. <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>
  2. //Input标签
  3. <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" />

发表评论

表情:
评论列表 (有 0 条评论,510人围观)

还没有评论,来说两句吧...

相关阅读