之前很簡單的認為對input的value監測就用2個事件可以搞定相容性,知道我看了司徒正美的這篇部落格,還是感慨自己不夠深入,接觸的太少。
對于IE全系列,可以采用onpropertychange屬性監測
對于 gte IE9 和W3c浏覽器,則通過input事件進行監測。
但是IE9的相容性可能會出現問題。
oninput 事件在使用者輸入、倒退(backspace)、删除(delete)、剪切(ctrl + x)、粘貼(ctrl + v)及滑鼠剪切與粘貼時觸發(在 IE9 中隻在輸入、粘貼、滑鼠粘貼時觸發)。
onpropertychange 事件在使用者輸入、倒退(backspace)、删除(delete)、剪切(ctrl + x)、粘貼(ctrl + v)及滑鼠剪切與粘貼時觸發(在 IE9 中隻在輸入、粘貼、滑鼠粘貼時觸發)(僅 IE 支援)。
是以可以這樣實作。
input = document.getElementById('input');
if(input.addEventListener){
input.addEventListener('input',fn,false);
}else{
input.attachEvent('onpropertychange',function(e){
if(e.propertyValue == 'value'){
fn();
}
});
}
if(window.VBArray && window.addEventListener && !window.WebSocket){
input.addEventListener('keyup',function(e){
var code = e.keycode || e.charcode;
if(code==8 || code==46){
fn();
}
},false) ;
input.oncut=function(){fn()};
}
另外,如果對不僅僅對文本内容進行監聽,而且要相應修改,那麼對于實作input事件的浏覽器而言,沒什麼
問題,而對于IE的propertychange事件,則應該有所注意--為了避免循環處罰該事件,需要在修改屬性之前将onpropertychange
處理程式取消,屬性修改完畢之後重新指派:
下面是一個簡單的強制輸入大寫字母的demo,來源自David Flanagan
1 function forceToUpperCase(element) {
2 if (typeof element === "string") element = document.getElementById(element);
3 element.oninput = upcase;
4 element.onpropertychange = upcaseOnPropertyChange;
5
6 // Easy case: the handler for the input event
7 function upcase(event) { this.value = this.value.toUpperCase(); }
8 // Hard case: the handler for the propertychange event
9 function upcaseOnPropertyChange(event) {
10 var e = event || window.event;
11 // If the value property changed
12 if (e.propertyName === "value") {
13 // 避免循環觸發事件
14 this.onpropertychange = null;
15 // Change the value to all uppercase
16 this.value = this.value.toUpperCase();
17 // 重新添加處理函數
18 this.onpropertychange = upcaseOnPropertyChange;
19 }
20 }
21 }