猿问

怎样让input type=number不能输入负数

怎样让number类型的不能输入负数,比如我输入-1,会马上变回1 ,也不能为空!

烙印99
浏览 13621回答 1
1回答

侃侃无极

基本的屏蔽上下箭头减少:<input type="number" name="number" min="1" max="10" />屏蔽手动输入,使用js监听oninput ,自动去掉 -即可需要注意的是,如果number输入的内容不是正确的数字,获取到的value是空的<body>&nbsp; &nbsp; <input type="number" name="" id="number" min = 0 ></body><script>&nbsp; &nbsp; document.getElementById("number").addEventListener("input",function(event){&nbsp; &nbsp; &nbsp; &nbsp;event.target.value = event.target.value.replace(/\-/g,"");&nbsp;&nbsp; &nbsp; });</script>【更新】使用keypress的判断&nbsp; &nbsp; document.getElementById("number").addEventListener("keypress",function(event){&nbsp; &nbsp; &nbsp; &nbsp; if(event.keyCode == 45){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; event.preventDefault();&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; });
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答