compositionstart
compositionstart是输入组合文字的时候触发,例如中文之类的
compositionend
当文本段落的组成完成或取消时, compositionend 事件将被触发,例如中文输入完成时
vue的源码在实现v-model的时候,也是添加了对组合事件的监听,这样在输入的时候就不会更新v-model的值
效果如下
<!DOCTYPE html>
<!--[if lt IE 7]> <html class="no-js lt-ie9 lt-ie8 lt-ie7"> <![endif]-->
<!--[if IE 7]> <html class="no-js lt-ie9 lt-ie8"> <![endif]-->
<!--[if IE 8]> <html class="no-js lt-ie9"> <![endif]-->
<!--[if gt IE 8]> <html class="no-js"> <!--<![endif]-->
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<title></title>
<meta name="description" content="" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="stylesheet" href="" />
</head>
<body>
<div>
<label>添加了compositionstart和onCompositionEnd事件</label>
<input type="text" id="inputValue" />
<span id="showValue"></span>
</div>
<div>
<label>未添加</label>
<input type="text" id="inputValueNo" />
<span id="showValueNo"></span>
</div>
<script>
let input = document.getElementById("inputValue");
let show = document.getElementById("showValue");
input.value = "有";
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); // 组合输入结束
let inputNo = document.getElementById("inputValueNo");
let showNo = document.getElementById("showValueNo");
inputNo.value = "未";
showNo.innerText = inputNo.value;
inputNo.addEventListener("input", onInputChangeNo);
function onInputChangeNo(e) {
showNo.innerText = e.target.value;
}
</script>
</body>
</html>