原生 <select> 樣式難控制,常需用 <div>+<ul> 模擬。本文提供含搜尋過濾、鍵盤導航、多實例隔離的完整組件雛形。
function showExpand(inputId, listId, listClass) {
// 關閉其他同類下拉
if (listClass) $('.' + listClass).hide();
var $input = $('#' + inputId);
var $list = $('#' + listId);
// 定位:輸入框下方
var rect = $input[0].getBoundingClientRect();
$list.css({ left: rect.left + 'px', top: rect.bottom + 'px' }).show();
// 選項點擊賦值
$list.find('li').off('click').on('click', function() {
$input.val($(this).text()).focus();
$list.hide();
});
}
function filterList(inputId, listId) {
var $input = $('#' + inputId);
var $list = $('#' + listId);
var kw = $input.val().toUpperCase();
$list.find('a').each(function() {
var $li = $(this).parent();
$(this).text().toUpperCase().indexOf(kw) === -1 ? $li.hide() : $li.show();
});
}
$('#txt_city').on('focus', function() { showExpand('txt_city', 'city_select1', 'expand'); })
.on('keyup', function() { filterList('txt_city', 'city_select1'); });
$('#txt_city2').on('focus', function() { showExpand('txt_city2', 'city_select2', 'expand'); })
.on('keyup', function() { filterList('txt_city2', 'city_select2'); });
<input type="text" id="txt_city" class="input_expand">
<a href="#" onclick="showExpand('txt_city','city_select1','expand')">▼</a>
<div class="expand" id="city_select1">
<ul>
<li><a href="#">SH 上海</a></li>
<li><a href="#">BJ 北京</a></li>
<li><a href="#">HZ 杭州</a></li>
</ul>
</div>
.expand { display:none; position:absolute; width:200px; max-height:150px; overflow-y:auto; border:1px solid #ccc; background:#fff; z-index:100; }
.expand li { margin:1px 0; }
.expand a { display:block; padding:2px 8px; text-decoration:none; }
.expand a:hover { background:#ff9; }
role="combobox"、aria-expanded、aria-controls。Enter/Esc/↑↓ 鍵盤操作。