原生 <select> 僅能選不能輸入,且無原生懸浮提示。本文提供一套原生 JS 增強方案:鍵盤輸入修改選項、懸浮顯示完整文字、Esc 恢復、Enter 確認。
keydown/keypress 捕獲字符,實時修改當前選項 text 與 value。onchange。onmouseover 顯示完整選項文字,onmouseout 隱藏。var oldValue, oldText;
function catch_keydown(sel) {
switch(event.keyCode) {
case 13: event.returnValue = false; break; // Enter
case 27: sel.options[sel.selectedIndex].text = oldText; // Esc
sel.options[sel.selectedIndex].value = oldValue;
event.returnValue = false; break;
case 8: // Backspace
var s = sel.options[sel.selectedIndex].text.slice(0,-1);
if (sel.options[sel.selectedIndex].value === oldText) sel.options[sel.selectedIndex].value = s;
sel.options[sel.selectedIndex].text = s;
event.returnValue = false; break;
}
}
function catch_press(sel) {
if (sel.selectedIndex >= 0) {
var s = sel.options[sel.selectedIndex].text + String.fromCharCode(event.keyCode);
if (sel.options[sel.selectedIndex].value === oldText) sel.options[sel.selectedIndex].value = s;
sel.options[sel.selectedIndex].text = s;
event.returnValue = false;
}
}
function catch_focus(sel) { oldText = sel.options[sel.selectedIndex].text; oldValue = sel.options[sel.selectedIndex].value; }
function selMouseOver(obj) {
var hint = document.all.div_hint;
hint.innerText = ' ' + obj.options[obj.selectedIndex].text + ' ';
if (hint.innerText.length > 2) { hint.style.display='block'; hint.style.left=event.clientX+16; hint.style.top=event.clientY; }
}
function selMouseOut() { document.all.div_hint.style.display='none'; }
<select style="width:130px;z-index:-1" name="tmpSel"
onmouseout="selMouseOut(this)"
onkeydown="catch_keydown(this)"
onfocus="catch_focus(this)">
<option value=""></option>
</select>
<div id="div_hint"></div>
<datalist> + <input list="...">:原生支援輸入建議,無需 JS。原生增強方案適合極簡環境或維護舊代碼;新專案優先用標準組件或成熟庫。