html5 oninput即時監聽輸入框值變化的完美方案

來源:互聯網
上載者:User

標籤:family   this   監聽   modify   屬性   mod   rip   支援   lease   

在網頁開發中經常會碰到需要動態監聽輸入框值變化的情況,如果使用 onkeydown、onkeypress、onkeyup 這個幾個鍵盤事件來監測的話,監聽不了右鍵的複製、剪貼和粘貼這些操作,處理組合快速鍵也很麻煩。因此這篇文章向大家介紹一種完美的解決方案:結合html5標準事件 oninput 和 IE 專屬事件 onpropertychange 事件來監聽輸入框值變化。,對於檢測 textarea, input:text, input:password 和 input:search 這幾個元素通過使用者介面發生的內容變化非常有用,在內容修改後立即被觸發,不像 onchange 事件需要失去焦點才觸發。主流瀏覽器基本都支援oninput事件,IE9以下不支援,需要使用 IE 特有的 onpropertychange 事件替代,這個事件在使用者介面改變或者使用指令碼直接修改內容兩種情況下都會觸發,有以下幾種情況:

  • 修改了 input:checkbox 或者 input:radio 元素的選擇中狀態, checked 屬性發生變化。
  • 修改了 input:text 或者 textarea 元素的值,value 屬性發生變化。
  • 修改了 select 元素的選中項,selectedIndex 屬性發生變化。

  在監聽到onpropertychange事件後,可以使用 event 的 propertyName 屬性來擷取發生變化的屬性名稱。

  集合 oninput & onpropertychange 監聽輸入框內容變化的範例程式碼如下:

<head>    <script type="text/javascript">    // Firefox, Google Chrome, Opera, Safari, Internet Explorer from version 9        function OnInput (event) {            alert ("The new content: " + event.target.value);        }    // Internet Explorer        function OnPropChanged (event) {            if (event.propertyName.toLowerCase () == "value") {                alert ("The new content: " + event.srcElement.value);            }        }    </script></head><body>    Please modify the contents of the text field.    <input type="text" oninput="OnInput (event)" onpropertychange="OnPropChanged (event)" value="Text field" /></body>

使用jQuery的話,只需要同時綁定 oninput 和 onpropertychange 兩個事件就可以了,範例程式碼如下:

$(‘input‘).on(‘input propertychange‘, function() {    alert($(this).val().length + ‘ characters‘);});

html5 oninput即時監聽輸入框值變化的完美方案

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.