文本框的属性监测

时间:2022-05-04
本文章向大家介绍文本框的属性监测,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

之前很简单的认为对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 }