要求:input中只能写入数字
方案一:
<input type="text" name="" oninput="value=value.replace(/[^\d]/g,'')">
方案二:vue中
<template>
<div>
<input type="text"
@input="change"
@change="change"
:value="inputValue">
</div>
</template>
<script>
export default {
data () {
return {
inputValue: null,
// timeid: null
}
},
methods: {
change (event) {
//if (this.timeid) {
//clearTimeout(this.timeid)
//}
// this.timeid = setTimeout(() => {
let val = event.target.value.trim()
val = Number(val)
if (!isNaN(val)) {
this.inputValue = val
console.log('输入数字' + this.inputValue)
} else {
console.log(`输入非数字${this.inputValue}`)
event.target.value = this.inputValue
}
// })
}
},
}
</script>
image.png
image.png
在方案1与方案2中,当输入o的时候,input事件会触发2次,此时点击空格之后,数字会减少一位.
待解决.
网友评论