<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>上下键选择联想词并输入到搜索框效果</title>
<style>
.selected {
background-color: #f5f5f5;
}
</style>
</head>
<body>
<div id="search-suggest" style="display: block;">
<div class="suggest-item">233300是哪里的邮编</div>
<div class="suggest-item">233300大写</div>
<div class="suggest-item">2333000</div>
<div class="suggest-item">32000000平方米等于多少公顷</div>
<div class="suggest-item">2333000大写</div>
<div class="suggest-item">233300日元</div>
<div class="suggest-item">23330000</div>
<div class="suggest-item">23330075</div>
<div class="suggest-item">233300CPU</div>
<div class="suggest-item">23330003</div>
</div>
<input id="kw" type="text" placeholder="搜索框" autocomplete="off">
<script>
var suggestItems = document.getElementsByClassName("suggest-item");
var searchBox = document.getElementById("kw");
var selectedIndex = -1;
// 监听键盘事件
searchBox.addEventListener("keydown", function (event) {
if (event.keyCode == 38) { // 上箭头
event.preventDefault();
if (selectedIndex > 0) {
selectedIndex--;
} else {
selectedIndex = suggestItems.length - 1;
}
updateSelectedSuggestion();
} else if (event.keyCode == 40) { // 下箭头
event.preventDefault();
if (selectedIndex < suggestItems.length - 1) {
selectedIndex++;
} else {
selectedIndex = 0;
}
updateSelectedSuggestion();
} else if (event.keyCode == 13) { // 回车键
event.preventDefault();
if (selectedIndex >= 0) {
searchBox.value = suggestItems[selectedIndex].textContent;
hideSuggestions();
}
}
});
// 更新选中的联想词样式
function updateSelectedSuggestion() {
for (var i = 0; i < suggestItems.length; i++) {
suggestItems[i].classList.remove("selected");
}
suggestItems[selectedIndex].classList.add("selected");
searchBox.value = suggestItems[selectedIndex].textContent;
}
// 隐藏联想词
function hideSuggestions() {
document.getElementById("search-suggest").style.display = "none";
}
</script>
</body>
</html>