js右下角实现剩余字数
<input type='text' [(ngModel)]='purpose' (input)="checkLength(purpose)"
maxlength='20' placeHolder="最多输入20字符">
<span>剩余{{purposeLength}}字</span>
<script>
checkLength(purpose){
setTimeout(()=>{
let length = this.purpose.length;
this.purposeLength = 20 - length;
if(this.purposeLength <= 0){
this.purposeLength = 0
}
},0);
}
</script>
注意⚠️
如果是对中文进行长度判断,在输入中文时,由于input事件在拼写汉字的过程中会触发,所以将长度判断的逻辑放在setTimeout函数中处理,这样会把这段逻辑处理放在另一个事件回调队列中,那么英文字母不需要这样。
此方法是基于angular,原生只需对input框绑定input监听,判断input框输入的value长度。