-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathinput.html
116 lines (110 loc) · 3.55 KB
/
input.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>auto complete</title>
<style>
* {
box-sizing: border-box;
margin: 0;
padding: 0;
}
#input {
width: 300px;
height: 30px;
margin: 0 auto;
}
ul {
list-style: none;
margin: 0 auto;
width: 300px;
background-color:lightpink;
color: white;
}
li {
cursor: pointer;
height: 30px;
}
#wrapper {
width: 300px;
margin: 200px auto;
position: relative;
}
.selected {
background-color:red;
}
</style>
</head>
<body>
<div id='wrapper'>
<input type= "text" id="input"/>
<ul id="ul">
</ul>
</div>
<script src="http://code.jquery.com/jquery-2.1.1.min.js"></script>
<script>
const arr = ['12345678','122222', 'apple', 'app','axio','bear','ball', 'banana', 'box'];
const ele = document.getElementById('input');
const ul = document.getElementById('ul');
let liSelected;
//监听input框输入
ele.addEventListener('input', function(e){
const value = e.target.value.trim();
if(value) {
getListData(value);
keyboardEvent();
} else {
ul.innerHTML = "";
}
});
//从数组中选中匹配的下拉
function getListData(inputValue) {
const lis = [];
arr.forEach(function(item) {
if(item.startsWith(inputValue) && inputValue) {
lis.push(`<li>${item}</li>`);
}
})
ul.innerHTML = lis.join("");
}
//处理键盘上下键选择和enter键选中
function keyboardEvent() {
let listItems = $('li');
$('input').keydown(function(e) {
var key = e.keyCode,
selected = listItems.filter('.selected'),
current;
if(key !== 40 && key !== 38 && key !==13) return;
listItems.removeClass('selected');
if(key == 40) { //down key
if( !selected.length || selected.is(':last-child')) {
current = listItems.eq(0);
}else {
current = selected.next();
}
}else if(key == 38) { //up key
if( !selected.length || selected.is(':first-child')) {
current = listItems.last();
}else {
current = selected.prev();
}
}else if(key == 13){//enter key
current = selected;
ele.value = current.text();
}
current.addClass('selected');
})
}
//处理下拉鼠标选择
ul.addEventListener('click', function(e) {
const ev = e || window.event;
const target = e.target || e.srcElement;
if(target.nodeName.toLowerCase() == 'li') {
ele.value = target.innerHTML;
}
});
</script>
</body>
</html>