我想添加一个基于 jQuery 自动完成的解决方案来完成这项工作。
第 1 步:使列表固定高度和可滚动
从https://jqueryui.com/autocomplete/ “可滚动”示例获取代码,将最大高度设置为结果列表,使其表现为选择框。
第 2 步:打开焦点列表:
在焦点事件上显示 jquery ui 自动完成列表
第 3 步:将最小字符数设置为 0,这样无论输入中有多少字符,它都会打开
最后结果:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>jQuery UI Autocomplete - Scrollable results</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<style>
.ui-autocomplete {
max-height: 100px;
overflow-y: auto;
/* prevent horizontal scrollbar */
overflow-x: hidden;
}
/* IE 6 doesn't support max-height
* we use height instead, but this forces the menu to always be this tall
*/
* html .ui-autocomplete {
height: 100px;
}
</style>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
var availableTags = [
"ActionScript",
"AppleScript",
"Asp",
"BASIC",
"C",
"C++",
"Clojure",
"COBOL",
"ColdFusion",
"Erlang",
"Fortran",
"Groovy",
"Haskell",
"Java",
"JavaScript",
"Lisp",
"Perl",
"PHP",
"Python",
"Ruby",
"Scala",
"Scheme"
];
$( "#tags" ).autocomplete({
// source: availableTags, // uncomment this and comment the following to have normal autocomplete behavior
source: function (request, response) {
response( availableTags);
},
minLength: 0
}).focus(function(){
// $(this).data("uiAutocomplete").search($(this).val()); // uncomment this and comment the following to have autocomplete behavior when opening
$(this).data("uiAutocomplete").search('');
});
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>
在此处检查 jsfiddle:
https://jsfiddle.net/bao7fhm3/1/