这是基本结构
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>中文输入法的高频事件</title>
</head>
<body>
<input type="text" class="txt" />
<script>
var inp = document.querySelector("input");
function search() {
console.log("搜索:" + inp.value);
}
inp.addEventListener("input", function () {
search();
});
</script>
</body>
</html>
输出:
发现在中文还没选中就触发了,现在希望没选中不要触发
改写代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>中文输入法的高频事件</title>
</head>
<body>
<input type="text" class="txt" />
<script>
var inp = document.querySelector("input");
function search() {
console.log("搜索:" + inp.value);
}
inp.addEventListener("input", function () {
search();
});
inp.addEventListener("compositionstart", () => {
console.log("中文输入开始");
});
inp.addEventListener("compositionend", () => {
console.log("中文输入结束");
});
</script>
</body>
</html>
打印结果:
我们要做的是从开始到结束中间的过程过滤掉,不触发搜索
直接上代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>中文输入法的高频事件</title>
</head>
<body>
<input type="text" class="txt" />
<script>
var inp = document.querySelector("input");
function search() {
console.log("搜索:" + inp.value);
}
let isComposition = false;
inp.addEventListener("input", function () {
if (isComposition) {
return;
}
search();
});
inp.addEventListener("compositionstart", () => {
isComposition = true;
console.log("中文输入开始");
});
inp.addEventListener("compositionend", () => {
isComposition = false;
console.log("中文输入结束");
search();
});
</script>
</body>
</html>
完美解决