oninput,onpropertychange,onchange的使用方法和差別

來源:互聯網
上載者:User

標籤:style   http   color   java   使用   io   art   ar   

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屬性

<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的屬性,需例如以下:

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);}

 

其餘函數

 

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";

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.