# ❓ input 搜索如何防抖,如何处理中文输入
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>Jeff</title>
</head>
<body>
<input type="text" id="input" />
<script>
const input = document.getElementById('input')
// 节流
input.addEventListener(
'input',
function (e) {
inputDebounce(e.target.value)
},
false
)
var inputDebounce = debounce(function (value) {
console.log(value)
})
function debounce(func, delay) {
if (!delay) delay = 300
let timer = null
return function () {
if (timer) clearTimeout(timer)
timer = setTimeout(() => {
if (func) func.apply(this, arguments)
}, delay)
}
}
// 中文限制
// 使用原生方法
// compositionstart 事件触发于一段文字的输入之前(类似于 keydown 事件,但是该事件仅在若干可见字符的输入之前,而这些可见字符的输入可能需要一连串的键盘操作、语音识别或者点击输入法的备选词)简单来说就是切换中文输入法时在打拼音时(此时input内还没有填入真正的内容),会首先触发compositionstart。
// 然后每打一个拼音字母,触发compositionupdate。
// 最后将输入好的中文填入input中时触发compositionend。触发compositionstart时,文本框会填入 “虚拟文本”(待确认文本),同时触发input事件;在触发compositionend时,就是填入实际内容后(已确认文本),所以这里如果不想触发input事件的话就可以设置一个bool变量来控制。
// input.addEventListener(
// 'compositionstart',
// function (e) {
// console.log('compositionstart')
// e.target.composing = false
// },
// false
// )
// input.addEventListener(
// 'compositionend',
// function (e) {
// console.log('compositionend')
// e.target.composing = true
// },
// false
// )
// input.addEventListener(
// 'change',
// function (e) {
// console.log('e.target.composing->change', e.target.composing)
// if (!e.target.composing) return
// console.log(e.target.value)
// },
// false
// )
// input.addEventListener(
// 'input',
// function (e) {
// console.log('e.target.composing->input', e.target.composing)
// if (!e.target.composing) return
// console.log(e.target.value)
// },
// false
// )
</script>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79