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

前言

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

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

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

jQuery用法

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

原生Js

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

转: https://blog.csdn.net/idomyway/article/details/79078625

原文地址:https://www.cnblogs.com/fps2tao/p/9440878.html