在Web开发中,我们经常需要限制用户只能输入数字。以下是实现方法:
<input type="number" min="0" step="1" oninput="this.value=this.value.replace(/[^0-9]/g,'');">
为输入框添加CSS样式实现自动换行:
<style>
.number-input {
white-space: pre-wrap;
word-wrap: break-word;
height: auto;
}
</style>
function removeTrailingZeros(value) {
return value.toString().replace(/(\.\d*?[1-9])0+$|\..0+$/, '$1');
}
document.querySelector('input').addEventListener('blur', function() {
this.value = removeTrailingZeros(this.value);
});
<input
type="number"
class="number-input"
min="0"
step="1"
oninput="this.value=this.value.replace(/[^0-9]/g,'');"
onblur="this.value=removeTrailingZeros(this.value)"
>
inputmode="numeric"属性onkeypress事件替代oninputpadding和border美化输入框通过以上方法,您可以轻松创建一个符合需求的数字输入框,既保证了用户体验,又确保了数据格式的正确性。