完整範例
<input type="text" id="txt" />
<ul id="sug" style="display:none; position:absolute; background:#fff; border:1px solid #ccc; width:200px; max-height:200px; overflow:auto;"></ul>
<script src="https://cdn.jsdelivr.net/npm/jquery@3.6.0/dist/jquery.min.js"></script>
<script>
var data = ["蘋果", "香蕉", "橘子", "葡萄", "西瓜", "鳳梨", "芒果"];
var $txt = $("#txt"), $sug = $("#sug"), selIdx = -1;
$txt.on("input", function() {
var kw = $txt.val();
$sug.empty().hide();
if (!kw) return;
data.filter(x => x.includes(kw)).forEach(function(v) {
$sug.append($("<li>").text(v).css({padding:"5px", cursor:"pointer"}));
});
$sug.show();
selIdx = -1;
});
$txt.on("keydown", function(e) {
var $lis = $sug.find("li");
if (!$lis.length) return;
if (e.key === "ArrowDown") { selIdx = (selIdx + 1) % $lis.length; highlight(); e.preventDefault(); }
else if (e.key === "ArrowUp") { selIdx = (selIdx - 1 + $lis.length) % $lis.length; highlight(); e.preventDefault(); }
else if (e.key === "Enter" && selIdx >= 0) { $txt.val($lis.eq(selIdx).text()); $sug.hide(); }
});
function highlight() {
$sug.find("li").removeClass("hl").eq(selIdx).addClass("hl");
}
$("<style>.hl{background:#337ab7;color:#fff}</style>").appendTo("head");
$sug.on("click", "li", function() {
$txt.val($(this).text());
$sug.hide();
});
$(document).on("click", function(e) {
if (!$(e.target).closest("#txt, #sug").length) $sug.hide();
});
</script>
特點
- 純 jQuery,無額外依賴。
- 支援鍵盤上下鍵循環選擇、Enter 填入、滑鼠點擊、點擊外部關閉。
- 易於擴充:AJAX 遠端搜尋、分組顯示、高亮關鍵字等。