1. 程式人生 > >input框設定onKeypress事件只能輸入數字(相容火狐和IE9)

input框設定onKeypress事件只能輸入數字(相容火狐和IE9)

https://segmentfault.com/q/1010000008818447

使用onInput()事件

oninput 是 HTML5 的標準事件,對於檢測 textarea, input:text, input:password 和 input:search 這幾個元素通過使用者介面發生的內容變化非常有用,在內容修改後立即被觸發,不像 onchange 事件需要失去焦點才觸發。oninput 事件在主流瀏覽器的相容情況如下:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>RunJS</title>
    </head>
    <body>
        <input type="text" onInput ="keypress(this)" />
    </body>
    </body>
</html>

// scripts
function keypress(_this){
    _this.value = _this.value.replace(/[^0-9]/g, '');
}