查看在线实例:
https://c.runoob.com/codedemo/6190
基础 HTML 代码
实例
<
form
autocomplete
=
"
off
"
action
=
"
/index.php
"
>
<
div
class
=
"
autocomplete
"
style
=
"
width:300px;
"
>
<
input
id
=
"
myInput
"
type
=
"
text
"
name
=
"
s
"
placeholder
=
"
请输入搜索内容
"
>
</
div
>
<
input
type
=
"
submit
"
>
</
form
>
再准备基础的搜索测试数据,是一个 JavaScript 数组:
var sites = ["Google","Taobao","Runoob","Wiki","Zhihu","Baidu","Sina","Tmall","JD","Alibaba","QQ","Weixin"];
以下搜索搜索框和联想菜单的样式:
实例
*
{
box-sizing:
border-box
;
}
body
{
font:
16
px
Arial
;
.autocomplete
{
position:
relative
;
display:
inline-block
;
input
{
border:
1
px
solid
transparent
;
background-color:
#f1f1f1
;
padding:
10
px
;
font-size:
16
px
;
input
[
type
=
text
]
{
background-color:
#f1f1f1
;
width:
100
%
;
input
[
type
=
submit
]
{
background-color:
DodgerBlue
;
color:
#fff
;
.autocomplete-items
{
position:
absolute
;
border:
1
px
solid
#d4d4d4
;
border-bottom:
none
;
border-top:
none
;
z-index:
99
;
top:
100
%
;
left:
0
;
right:
0
;
.autocomplete-items
div
{
padding:
10
px
;
cursor:
pointer
;
background-color:
#fff
;
border-bottom:
1
px
solid
#d4d4d4
;
.autocomplete-items
div
:hover
{
background-color:
#e9e9e9
;
.autocomplete-active
{
background-color:
DodgerBlue
!
important
;
color:
#ffffff
;
以下是搜索搜索框和联想菜单的 JavaScript 代码:
实例
function
autocomplete
(
inp
,
arr
)
{
var
currentFocus
;
inp
.
addEventListener
(
"
input
"
,
function
(
e
)
{
var
a
,
b
,
i
,
val
=
this
.
value
;
closeAllLists
(
)
;
if
(
!
val
)
{
return
false
;
}
currentFocus
= -
1
;
a
=
document
.
createElement
(
"
DIV
"
)
;
a
.
setAttribute
(
"
id
"
,
this
.
id
+
"
autocomplete-list
"
)
;
a
.
setAttribute
(
"
class
"
,
"
autocomplete-items
"
)
;
this
.
parentNode
.
appendChild
(
a
)
;
for
(
i
=
0
;
i
<
arr
.
length
;
i
++
)
{
if
(
arr
[
i
]
.
substr
(
0
,
val
.
length
)
.
toUpperCase
(
)
==
val
.
toUpperCase
(
)
)
{
b
=
document
.
createElement
(
"
DIV
"
)
;
b
.
innerHTML
=
"
<strong>
"
+
arr
[
i
]
.
substr
(
0
,
val
.
length
)
+
"
</strong>
"
;
b
.
innerHTML
+=
arr
[
i
]
.
substr
(
val
.
length
)
;
b
.
innerHTML
+=
"
<input type='hidden' value='
"
+
arr
[
i
]
+
"
'>
"
;
b
.
addEventListener
(
"
click
"
,
function
(
e
)
{
inp
.
value
=
this
.
getElementsByTagName
(
"
input
"
)
[
0
]
.
value
;
closeAllLists
(
)
;
}
)
;
a
.
appendChild
(
b
)
;
}
)
;
inp
.
addEventListener
(
"
keydown
"
,
function
(
e
)
{
var
x
=
document
.
getElementById
(
this
.
id
+
"
autocomplete-list
"
)
;
if
(
x
)
x
=
x
.
getElementsByTagName
(
"
div
"
)
;
if
(
e
.
keyCode
==
40
)
{
currentFocus
++;
addActive
(
x
)
;
}
else
if
(
e
.
keyCode
==
38
)
{