遇到如此需求,首先想到的是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'); }); } }) }