`

jquery - 实时监听input输入的变化(兼容主流浏览器)

 
阅读更多

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

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

1,内嵌元素方式(属性编辑方式)(该方式在IE中测试通过,非IE有待完善)

<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');
            });
        }
    })
}

 

出自: http://www.cnblogs.com/asie-huang/archive/2012/07/10/2585038.html

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics