在 Web 開發中經常會碰到需要動態監聽輸入框值變化的情況,如果使用 onkeydown、onkeypress、onkeyup 這個幾個鍵盤事件來監測的話,監聽不了右鍵的復制、剪貼和粘貼這些操作,處理組合快捷鍵也很麻煩。因此這篇文章向大家介紹一種完美的解決方案:結合 HTML5 標准事件 oninput 和 IE 專屬事件 onpropertychange 事件來監聽輸入框值變化。
您可能感興趣的相關文章
oninput 是 HTML5 的標准事件,對於檢測 textarea, input:text, input:password 和 input:search 這幾個元素通過用戶界面發生的內容變化非常有用,在內容修改后立即被觸發,不像 onchange 事件需要失去焦點才觸發。oninput 事件在主流瀏覽器的兼容情況如下:
從上面表格可以看出,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 兩個事件就可以了,示例代碼如下:
$('textarea').bind('input propertychange', function() { $('.msg').html($(this).val().length + ' characters'); });
下面是 JsFiddle 在線演示,如果不能顯示請刷新一下頁面或者點擊后面的鏈接(http://jsfiddle.net/PVpZf/):
最后需要注意的是:oninput 和 onpropertychange 這兩個事件在 IE9 中都有個小BUG,那就是通過右鍵菜單菜單中的剪切和刪除命令刪除內容的時候不會觸發,而 IE 其他版本都是正常的,目前還沒有很好的解決方案。不過 oninput & onpropertychange 仍然是監聽輸入框值變化的最佳方案,如果大家有更好的方法,歡迎參與討論。
參考資料:
- 《oninput event (Internet Explorer)》
- 《oninput event | input event》
- 《HTML5 Input Event Handlers and User-Experience》
- 《onpropertychange event | propertychange event》
- 《A HTML5 Browser maze, oninput support》
您可能感興趣的相關文章
本文鏈接:使用 oninput & onpropertychange 監聽輸入框
編譯來源:夢想天空 ◆ 關注前端開發技術 ◆ 分享網頁設計資源
hide