監聽文本框輸入(input & textarea)

基本概念html

Firefox、Chrome、IE9&IE9+ 均支持 oninput 事件,此外全部版本的 IE 均支持 onpropertychange 事件。前端

oninput 事件在用戶輸入、退格(backspace)、刪除(delete)、剪切(ctrl + x)、粘貼(ctrl + v)及鼠標剪切與粘貼時觸發(在 IE9 中只在輸入、粘貼、鼠標粘貼時觸發)。web

onpropertychange 事件在用戶輸入、退格(backspace)、刪除(delete)、剪切(ctrl + x)、粘貼(ctrl + v)及鼠標剪切與粘貼時觸發(在 IE9 中只在輸入、粘貼、鼠標粘貼時觸發)(僅 IE 支持)。spa

backspace、delete 兩個按鍵的 keyCode 分別爲 八、46。.net

oncut 事件在粘貼(ctrl + v)、鼠標粘貼時觸發。code

function fn () {
// do something
}
if (window.addEventListener) {
    input.addEventListener("input", fn);
} else {
   input.attachEvent("onpropertychange", fn);
}
if (!!window.attachEvent && navigator.userAgent.match(/msie (\d)/i)[1] > 8) {
     input.attachEvent("onkeydown", function () {
         var key = window.event.keyCode;
        (key == 8 || key == 46) && fn();
     });
     input.attachEvent("oncut", fn);
}

轉自: http://www.web92.net/760.html | WEB前端開發
htm

相關文章
相關標籤/搜索