HTML文本输入仅允许数字输入

HTML文本输入仅允许数字输入

是否有快速设置HTML文本输入的方法(<input type=text />)只允许数字击键(加上‘.’)?



蓝山帝景
浏览 2317回答 4
4回答

茅侃侃

使用这个DOM<input&nbsp;type='text'&nbsp;onkeypress='validate(event)'&nbsp;/>这个剧本function&nbsp;validate(evt)&nbsp;{ &nbsp;&nbsp;var&nbsp;theEvent&nbsp;=&nbsp;evt&nbsp;||&nbsp;window.event; &nbsp;&nbsp;//&nbsp;Handle&nbsp;paste &nbsp;&nbsp;if&nbsp;(theEvent.type&nbsp;===&nbsp;'paste')&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key&nbsp;=&nbsp;event.clipboardData.getData('text/plain'); &nbsp;&nbsp;}&nbsp;else&nbsp;{ &nbsp;&nbsp;//&nbsp;Handle&nbsp;key&nbsp;press &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;var&nbsp;key&nbsp;=&nbsp;theEvent.keyCode&nbsp;||&nbsp;theEvent.which; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;key&nbsp;=&nbsp;String.fromCharCode(key); &nbsp;&nbsp;} &nbsp;&nbsp;var&nbsp;regex&nbsp;=&nbsp;/[0-9]|\./; &nbsp;&nbsp;if(&nbsp;!regex.test(key)&nbsp;)&nbsp;{ &nbsp;&nbsp;&nbsp;&nbsp;theEvent.returnValue&nbsp;=&nbsp;false; &nbsp;&nbsp;&nbsp;&nbsp;if(theEvent.preventDefault)&nbsp;theEvent.preventDefault(); &nbsp;&nbsp;}}

小唯快跑啊

我已经很久很努力地想找到一个很好的答案,我们迫切需要<input type="number"但除此之外,这两种方法是我能想到的最简洁的方法:<input type="text"&nbsp;&nbsp; &nbsp; &nbsp; &nbsp;onkeyup="this.value=this.value.replace(/[^\d]/,'')">如果您不喜欢在被擦除之前瞬间显示不被接受的字符,下面的方法是我的解决方案。注意许多附加条件,这是为了避免禁用所有类型的导航和热键。如果有人知道如何压缩这个,让我们知道!<input type="text"&nbsp;onkeydown="return ( event.ctrlKey || event.altKey&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || (47<event.keyCode && event.keyCode<58 && event.shiftKey==false)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || (95<event.keyCode && event.keyCode<106)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || (event.keyCode==8) || (event.keyCode==9)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || (event.keyCode>34 && event.keyCode<40)&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; || (event.keyCode==46) )">
打开App,查看更多内容
随时随地看视频慕课网APP