如何使用html实现提示词在搜索框内以列表形式下拉也可以自己输入搜索词
时间: 2023-12-26 19:03:35 浏览: 265
可输入下拉框(html控件)
3星 · 编辑精心推荐
您可以使用HTML和JavaScript来实现这个功能。下面是一个简单的例子:
```html
<!DOCTYPE html>
<html>
<head>
<title>搜索框提示词</title>
<style>
#search-box {
position: relative;
display: inline-block;
}
#search-box input[type="text"] {
padding-right: 40px;
width: 200px;
}
#search-box ul {
position: absolute;
top: 100%;
left: 0;
z-index: 10;
background-color: #fff;
border: 1px solid #ccc;
list-style: none;
margin: 0;
padding: 0;
display: none;
max-height: 200px;
overflow-y: auto;
}
#search-box li {
padding: 5px;
cursor: pointer;
}
#search-box li:hover {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="search-box">
<input type="text" id="search-input" placeholder="搜索">
<ul id="search-results"></ul>
</div>
<script>
// 假设这是您的提示词列表
var words = ["苹果", "香蕉", "橘子", "草莓", "蓝莓", "猕猴桃", "西瓜", "芒果"];
var input = document.getElementById("search-input");
var results = document.getElementById("search-results");
// 监听输入框的输入事件
input.addEventListener("input", function() {
var value = input.value.trim().toLowerCase();
results.innerHTML = "";
if (value.length === 0) {
results.style.display = "none";
return;
}
// 遍历提示词列表,找到匹配的项
words.forEach(function(word) {
if (word.toLowerCase().indexOf(value) === 0) {
var li = document.createElement("li");
li.textContent = word;
li.addEventListener("click", function() {
input.value = word;
results.style.display = "none";
});
results.appendChild(li);
}
});
if (results.children.length > 0) {
results.style.display = "block";
} else {
results.style.display = "none";
}
});
// 监听输入框的聚焦和失焦事件
input.addEventListener("focus", function() {
if (results.children.length > 0) {
results.style.display = "block";
}
});
input.addEventListener("blur", function() {
results.style.display = "none";
});
// 监听键盘事件,实现上下键选择提示词
input.addEventListener("keydown", function(e) {
if (e.keyCode === 38) { // 上箭头
var selected = results.querySelector(".selected");
if (selected) {
selected.classList.remove("selected");
if (selected.previousSibling) {
selected = selected.previousSibling;
} else {
selected = results.lastChild;
}
} else {
selected = results.lastChild;
}
selected.classList.add("selected");
input.value = selected.textContent;
e.preventDefault();
} else if (e.keyCode === 40) { // 下箭头
var selected = results.querySelector(".selected");
if (selected) {
selected.classList.remove("selected");
if (selected.nextSibling) {
selected = selected.nextSibling;
} else {
selected = results.firstChild;
}
} else {
selected = results.firstChild;
}
selected.classList.add("selected");
input.value = selected.textContent;
e.preventDefault();
} else if (e.keyCode === 13) { // 回车键
var selected = results.querySelector(".selected");
if (selected) {
input.value = selected.textContent;
results.style.display = "none";
}
}
});
</script>
</body>
</html>
```
这里使用了一个 `ul` 元素作为提示词列表,当输入框输入时通过 JavaScript 动态生成并显示这个列表,用户可以通过鼠标点击或键盘选择列表项,也可以直接输入搜索词。
阅读全文