JS控制两个文本框文字
在IE中使用:onpropertychange,其他浏览器中使用:oninput
oninput,onpropertychange,onchange的用法
- onchange触发事件必须满足两个条件:
a)当前对象属性改变,并且是由键盘或鼠标事件激发的(脚本触发无效)
b)当前对象失去焦点(onblur);
- onpropertychange的话,只要当前对象属性发生改变,都会触发事件,但是它是IE专属的;
- oninput是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器,但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。
在textarea中,如果想捕获用户的键盘输入,用onkeyup检查事件就可以了,但是onkeyup并不支持复制和粘贴,因此需要动态监测textarea中值的变化,这就需要onpropertychange(用在IE浏览器)和oninput(非IE浏览器)结合在一起使用了。
1 if(isIE) 2 3 { 4 5 document.getElementById("wb_comment_content").onpropertychange = set_alert_wb_comment(); 6 7 } 8 9 else //需要用addEventListener来注册事件 10 11 { 12 13 document.getElementById("wb_comment_content").addEventListener("input", set_alert_wb_comment, false); 14 15 }
这次的需求是只有当文本框A的文字改变时才进行同步,因此在调用事件onpropertychange时需要做一个判断:
1 function ChangeText(text1,text2) 2 { 3 document.getElementById(text1).attachEvent('onpropertychange',function(o){ 4 if(o.propertyName!='value')return; //if not value changed return 5 //if value changed then set the text 6 document.getElementById(text2).value=document.getElementById(text1).value; 7 }); 8 }
在动态添加的控件时调用方式为:
1 'this script only can run in IE 2 Dim Str_ClientID As String = objWebCtrlInput.ClientID.ToString().Trim() 3 Dim IntLastNum As Int16 = Convert.ToInt16(Str_ClientID.Substring(Str_ClientID.LastIndexOf("_") + 1)) + 1 4 Dim New_ClientID As String = Str_ClientID.Substring(0, Str_ClientID.LastIndexOf("_") + 1) & Right("000" & IntLastNum.ToString(), 3) 5 'objWebCtrlInput.Attributes.Add("onfocus", "document.getElementById('" & New_ClientID & "').value=document.getElementById('" & Str_ClientID & "').value") 6 objWebCtrlInput.Attributes.Add("onpropertychange", "ChangeText('" & Str_ClientID & "','" & New_ClientID & "')") 7 'end add onpropertychange
通过判断改变的是否为value,实现了文字同步。
如果不进行属性为value的判断直接用在页面刷新时也会触发同步,不符合需要。
好的程序员,他们删掉的代码,比留下来的还要多很多。