類似限制輸入長度這種需求。
通常究抓、我們會添加監(jiān)聽:
<script >
var textInput = document.querySelector('#text_input');
textInput.addEventListener('input', function(){
if(this.value.length>=10){
this.value=this.value.substring(0,10)
}
});
</script>
這段代碼在英文屋灌、數(shù)字、符號輸入等情況下是沒有問題的。
但是在中文情況下:
web
app
也就是表示在用戶進行非直接輸入的時候质欲、監(jiān)聽事件也對用戶行為進行了處理树埠、這不是我們想要的。
所以嘶伟、我們需要用到兩個事件compositionstart 和 compositionend怎憋。
<script >
var textInput = document.querySelector('#text_input');
var inputLock = false;
textInput.addEventListener('compositionstart', function(){
inputLock = true;
})
textInput.addEventListener('compositionend', function(){
inputLock = false;
})
textInput.addEventListener('input', function(){
if(! inputLock){
if(this.value.length>=10){
this.value=this.value.substring(0,10)
}
};
});
</script>
compositionstart事件在用戶開始進行非直接輸入的時候觸發(fā)。
compositionend事件則在用戶進行直接輸入的時候觸發(fā)九昧。
通過一個開關(guān)inputLock绊袋。在用戶進行非直接輸入時不進行處理、改為直接輸入時再進行處理铸鹰。
web
app
有些瀏覽器或者手機版本下癌别。input監(jiān)聽和compositionend調(diào)用的順序可能會有先后。需要特殊注意蹋笼。