1、限制input最大長度
<input type="text" maxlength="5" /> //可以
<input type="number" maxlength="5" /> //沒有效果
<input type="number" οninput="if(value.length>5) value=value.slice(0,5)" /> //js控制,可以
<input type="tel" maxlength="5" /> //tel類型,可以
此外,tel類型的input在ios上會調出全數字鍵盤,而number類型的input則會調出帶有標點符號的鍵盤。
2、限制input輸入框為純數字:
a、onkeyup = "value=value.replace(/[^\d]/g,'')"
使用 onkeyup 事件,有 bug ,那就是在中文輸入法狀態下,輸入漢字之后直接回車,會直接輸入字母
b、onchange = "value=value.replace(/[^\d]/g,'')"
使用 onchange 事件,在輸入內容后,只有 input 喪失焦點時才會得到結果,並不能在輸入時就做出響應
c、oninput = "value=value.replace(/[^\d]/g,'')"
使用 oninput 事件,完美的解決了以上兩種問題,暫時還沒有出現其它問題。