基於監聽事件和通過正則處理字符串實現
一、原生JS
<body>
<input type="text" id="number" placeholder="只能輸入數字且最多兩位小數">
<script>
//獲取節點
let inp = document.getElementById('number');
//給節點添加鍵盤擡起事件
inp.onkeyup = function restrictNumber() {
let inpu = document.getElementById('number');
inpu.value = inpu.value.replace(/[^\d.]/g, ""); //僅保留數字和"."
inpu.value = inpu.value.replace(/\.{2,}/g, "."); //僅保留第一個"."
inpu.value = inpu.value.replace(".", "$#$").replace(/\./g, "").replace("$#$", ".");
inpu.value = inpu.value.replace(/^(\-)*(\d+)\.(\d\d).*$/, '$1$2.$3');//限制只能輸入兩個小數
if (inpu.value.indexOf(".") < 0 && inpu.value != "") { //首位是0的話去掉
inpu.value = parseFloat(inpu.value);
}
}
</script>
</body>
二、基於vue
<template>
<input type="text" @keyup ="keyU" v-model="value">
</template>
<script>
export default {
data(){
value:'',
},
methods: {
keyU(){
this.value = this.value.replace(/[^\d.]/g,""); //清除“數字”和“.”以外的字符
this.value = this.value.replace(/\.{2,}/g,"."); //只保留第一個. 清除多餘的
this.value = this.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能輸入兩個小數
if(this.value.indexOf(".")< 0 && this.value !=""){//以上已經過濾,此處控制的是如果沒有小數點,首位不能爲類似於 01、02的金額
this.value= parseFloat(this.value);
}
},
}
}
</script>
三、基於vue和element-ui
重點在於native修飾符,作用是監聽組件根元素的原生事件
<template>
<el-input v-model="showData.proportion" @keyup.native="keyU" ></el-input>
</template>
<script>
export default {
data(){
value:'',
},
methods: {
keyU(){
this.value = this.value.replace(/[^\d.]/g,""); //清除“數字”和“.”以外的字符
this.value = this.value.replace(/\.{2,}/g,"."); //只保留第一個. 清除多餘的
this.value = this.value.replace(".","$#$").replace(/\./g,"").replace("$#$",".");
this.value = this.value.replace(/^(\-)*(\d+)\.(\d\d).*$/,'$1$2.$3');//只能輸入兩個小數
if(this.value.indexOf(".")< 0 && this.value !=""){//以上已經過濾,此處控制的是如果沒有小數點,首位不能爲類似於 01、02的金額
this.value= parseFloat(this.value);
}
},
}
}
</script>