之前写过获得输入框输入的字节数
JS获得输入框输入的字节数
那么如果想限制输入框输入的字节数该怎么做呢?
比如限制字节数为20,示例代码如下:
<input @input="handleInput" v-model="inputValue"/>
data(){
return{
inputValue:''
}
},
methods:{
getStr(str,num){
let len = 0;
const chinese = /[^\x00-\xff]/ig;
for(let i=0;i<str.length;i++){
if(str.charAt(i).match(chinese)){
len +=2;
}else{
len +=1;
}
if(len > num){
return str.slice(0,i)
}
}
return str
},
handleInput(){
this.inputValue = this.getStr(this.inputValue,20)
}
}