設計稿上自訂的箭頭圖示、圓角、陰影,原生的 <select> 都做不到。既然無法靠 CSS 解決,就只能用 JS 加 div 自己刻一個。本文示範一個支援鍵入過濾的下拉選單。
<style type="text/css" media="all">
* { font-size:12px; line-height:18px; list-style:none;
padding:0; margin:0; text-decoration:none; color:#000; border:0 }
.page { text-align:center; margin:50px; }
input { border-bottom:solid 1px #ccc; height:18px }
.expand {
display:none; position:absolute; width:200px; height:100px;
overflow-y:auto; border:solid 1px #ccc;
}
.expand li { margin:1px 0; background:#fff }
.expand a { text-decoration:none; display:block;
padding:0 5px; background:#efefef; margin:1px 0 }
.expand a:hover { background:#ff9 }
</style>
function showExpand(targetId, expandId, expand_class) {
// 先關掉其他已展開的層,確保同一時間只有一個
if (expand_class != undefined) { $("." + expand_class).hide(); }
var expand = $("#" + expandId);
var target = $("#" + targetId);
var rect = target.get(0).getBoundingClientRect();
// 依瀏覽器微調位置(舊 IE 的邊框計算方式不同)
var dx = /* isIE ? -2 : 0 */;
var dy = /* isIE ? 17 : 19 */;
expand.get(0).style.left = (rect.left + dx) + "px";
expand.get(0).style.top = (rect.top + dy) + "px";
expand.show();
// 點擊項目後把文字填回輸入框
$("#" + expandId).find("li").each(function () {
$(this).show().click(function () {
target.val($(this).text().split(' ')[1]);
expand.hide();
});
});
}
function search(srcId, expandId) {
var expand = $("#" + expandId);
var src = $("#" + srcId);
var A = expand.find("a");
var v = src.val().toUpperCase();
A.each(function () {
if (v.length >= 2) {
// 至少輸入兩個字才開始過濾,避免打一個字就全部消失
$(this).parent().toggle(
$(this).text().toUpperCase().indexOf(v) != -1
);
} else {
$(this).parent().show();
}
});
src.val(v);
}
$().ready(function () {
$("#txt_city").keyup(function () {
search('txt_city', 'city_select1');
}).focus(function () {
showExpand('txt_city', 'city_select1', 'expand');
});
$("#txt_city2").keyup(function () {
search('txt_city2', 'city_select2');
}).focus(function () {
showExpand('txt_city2', 'city_select2', 'expand');
});
});
<div class="page">
<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="javascript:void(0)">SH 上海</a></li>
<li><a href="javascript:void(0)">BJ 北京</a></li>
<li><a href="javascript:void(0)">HZ 杭州</a></li>
<li><a href="javascript:void(0)">WH 武漢</a></li>
</ul>
</div>
</div>
這個做法能滿足視覺需求,但必須清楚它放棄了原生 select 的所有無障礙能力。使用原生 <select> 時,鍵盤上下鍵、Enter 確認、Esc 關閉、螢幕閱讀器朗讀「下拉選單,共六項,目前選取第二項」這些行為都是免費的。自製版本若不做額外處理,這些功能全部消失。
如果專案重視可及性,建議:
role="combobox"、role="listbox"、aria-expanded、aria-activedescendant 等 ARIA 屬性,並自行實作鍵盤操作。<select> 作為功能本體,只用 CSS 修飾箭頭(例如把 appearance: none 加上自訂背景圖),多數現代瀏覽器已支援,能同時拿到美觀與可用性。另一個實務建議:範例中用 getBoundingClientRect() 做定位,這在頁面捲動後座標會失準。若下拉層要能正確跟隨,請改用 position: fixed 搭配 clientX/clientY,或監聽 scroll 事件重新定位。