1、监听输入法输入开始和结束
compositionstart、compositionEnd分别监听输入开始和结束
2、在其他事件中获取到输入法组合状态
通过往e.target上定义一个composing属性,在compositionstart置为true,在compositionEnd置为false
即可实现在该元素的其他事件中监听到输入状态
代码实例:
// html
<input type="text" id="inputValue">
<span id="showValue"></span>
// js
<script>
let input = document.getElementById('inputValue');
let show = document.getElementById('showValue');
input.value = 123;
show.innerText = input.value
function onCompositionStart(e) {
e.target.composing = true;
}
function onCompositionEnd(e) {
if (!e.target.composing) {
return
}
e.target.composing = false;
show.innerText = e.target.value
}
function onInputChange(e) {
// e.target.composing表示是否还在输入中
if(e.target.composing)return;
show.innerText = e.target.value
}
input.addEventListener('input', onInputChange)
input.addEventListener('compositionstart', onCompositionStart)// 组合输入开始
input.addEventListener('compositionend', onCompositionEnd) // 组合输入结束
</script>