實時監聽輸入框值變化的完美方案:oninput & onpropertychange
阿新 • • 發佈:2017-09-18
ner 監聽 jpg number ima 方案 radio 技術 search
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 監聽輸入框內容變化的示例代碼如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
<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 兩個事件就可以了,示例代碼如下:
1 2 3 |
$( ‘textarea‘ ).bind( ‘input propertychange‘ , function () {
$( ‘.msg‘ ).html($( this ).val().length + ‘ characters‘ );
|
實時監聽輸入框值變化的完美方案:oninput & onpropertychange