• [转] 实时监听input输入的变化(兼容主流浏览器)


    遇到如此需求,首先想到的是change事件,但用过change的都知道只有在input失去焦点时才会触发,并不能满足实时监测的需求,比如监测用户输入字符数。

    在经过查阅一番资料后,欣慰的发现firefox等现代浏览器的input有oninput这一属性,可以用三种方式使用它:

    1,内嵌元素方式(属性编辑方式)

    <input id="test" oninput="console.log('input');" type="text" />

    2,句柄编辑方式

    document.getElementById('test').oninput=function(){
        console.log('input');
    }

    3,事件侦听方式(jquery)

    $('#test').on('input',function(){
    console.log('input');
    })

    但是,以上代码仅在除了ie的浏览器大大们里才work,那ie该怎么处理呢? 在ie中有一个属性叫做onpropertychange:

    <input id="test" onpropertychange="alert('change');" type="text" />

    经过调试后马上就会发现,这个属性是在元素的任何属性变化时都会起作用,包括我们这里所提到的value,但至少是起作用了,那接下来的任务就是筛选出property为value的变化。

    document.getElementById('test').attachEvent('onpropertychange',function(e) {
        if(e.propertyName!='value') return;
        $(that).trigger('input');
    });

    在上面代码中的回调函数中会传入一个参数,为该事件,该事件有很多属性值,搜寻一下可以发现有一个我们很关心的,叫做propertyName,也就是当前发生变化的属性名称。然后就相当简单了,只要在回调函数中判断一下是否为我们所要的value,是的话就trigger一下‘input’事件。

    然后,就可以在主流浏览器中统一用这样的方式来监听‘input’事件了。

    $('#test').on('input',function(){
        alert('input');
    })

    最后贴上完整代码:

    复制代码
    $('#test').on('input',function(){
        alert('input');
    })
    
    //for ie
    if(document.all){
        $('input[type="text"]').each(function() {
            var that=this;
    
            if(this.attachEvent) {
                this.attachEvent('onpropertychange',function(e) {
                    if(e.propertyName!='value') return;
                    $(that).trigger('input');
                });
            }
        })
    }
    复制代码
  • 相关阅读:
    c++爱问的面试问题
    Ognl底层使用
    [勘探开发]成绩,全栈开发,健全&amp;借贷
    FMS4
    Flex远程调用机制RemoteObject应用技巧
    Flex开发框架cairngorm入门实例
    RC1意思
    获取JAVA[WEB]项目相关路径的几种方法
    排序算法
    jQuery Validate
  • 原文地址:https://www.cnblogs.com/chris-oil/p/6662396.html
Copyright © 2020-2023  润新知