oninput,onpropertychange,onchange的用法和区别

1、前言

由于工作需要,需实现一个类似于微博输入框的功能,在用户动态输入文字的时候,修改提示“您还可以输入XX字”。如下图所示:

因此,稍微研究了一下oninput,onpropertychange,onchange的区别和用法,以及onpropertychange在ie浏览器下的一个bug。

2、oninput,onpropertychange,onchange的用法

l onchange触发事件必须满足两个条件:

a)当前对象属性改变,并且是由键盘或鼠标事件激发的(脚本触发无效)

b)当前对象失去焦点(onblur);

l onpropertychange的话,只要当前对象属性发生改变,都会触发事件,但是它是IE专属的;

l oninput是onpropertychange的非IE浏览器版本,支持firefox和opera等浏览器,但有一点不同,它绑定于对象时,并非该对象所有属性改变都能触发事件,它只在对象value值发生改变时奏效。

在textarea中,如果想捕获用户的键盘输入,用onkeyup检查事件就可以了,但是onkeyup并不支持复制和粘贴,因此需要动态监测textarea中值的变化,这就需要onpropertychange(用在IE浏览器)和oninput(非IE浏览器)结合在一起使用了。

3、代码实现:

第一种方法是直接写入textarea的onpropertychange和oninput属性

[c-sharp] view plaincopyprint?

  1. <textarea id="wb_comment_content" name="wb_comment_content" onblur="blur_wb_textarea(this);" onfocus="click_wb_textarea(this);" onpropertychange="set_alert_wb_comment();" oninput="set_alert_wb_comment();" class="gary666" style="font-size:12px;" mce_style="font-size:12px;">欢迎您每天来微评爱车哦……

<textarea id="wb_comment_content" name="wb_comment_content" onblur="blur_wb_textarea(this);" onfocus="click_wb_textarea(this);" onpropertychange="set_alert_wb_comment();" oninput="set_alert_wb_comment();" class="gary666" style="font-size:12px;" mce_style="font-size:12px;">欢迎您每天来微评爱车哦……

如果想要用JavaScript设置textarea的属性,需如下:

[c-sharp] view plaincopyprint?

  1. if(isIE)
  2. {
  3. document.getElementById("wb_comment_content").onpropertychange = set_alert_wb_comment();
  4. }
  5. else //需要用addEventListener来注册事件
  6. {
  7. document.getElementById("wb_comment_content").addEventListener("input", set_alert_wb_comment, false);
  8. }

if(isIE) { document.getElementById("wb_comment_content").onpropertychange = set_alert_wb_comment(); } else //需要用addEventListener来注册事件 { document.getElementById("wb_comment_content").addEventListener("input", set_alert_wb_comment, false); }

其余函数

[c-sharp] view plaincopyprint?

  1. function click_wb_textarea(obj)
  2. {
  3. if(obj.value==obj.defaultValue)
  4. {
  5. obj.value="";
  6. }
  7. //obj.className=""; //这样设置类名在ie下会有在输入第一个字符的时候onpropertychange不会触发的bug
  8. obj.style.color="#000";
  9. return false;
  10. }
  11. function blur_wb_textarea(obj)
  12. {
  13. if(obj.value=="")
  14. {
  15. //obj.className="gary666";
  16. obj.style.color="#666";
  17. obj.value= obj.defaultValue;
  18. }
  19. return false;
  20. }

function click_wb_textarea(obj) { if(obj.value==obj.defaultValue) { obj.value=""; } //obj.className=""; //这样设置类名在ie下会有在输入第一个字符的时候onpropertychange不会触发的bug obj.style.color="#000"; return false; } function blur_wb_textarea(obj) { if(obj.value=="") { //obj.className="gary666"; obj.style.color="#666"; obj.value= obj.defaultValue; } return false; }

4、onpropertychange的bug

在代码实现时,发现在响应用户onclick了textarea时,如果使用obj.className="XX";来改变textarea输入框中字体的样式,会导致在ie下会有在输入第一个字符的时候onpropertychange不会触发的bug,因此需要这样设置:obj.style.color="#000";

    网购从这里开始 ( 物美价廉还等什么?!!! )
原文地址:https://www.cnblogs.com/suizhikuo/p/2490712.html