很多網站都有這種效果:在文字框輸入字元,下方立刻跳出相符的候選清單,還能用上下鍵選擇、Enter 確認。本文拆解它的實作細節。範例中的候選資料是寫死在頁面的靜態陣列,實務上只要換成 AJAX 從資料庫取即可。
<style>
body, div { font-family: verdana; line-height: 100%; font-size: 10pt; }
input { width: 320px; }
h1 { text-align: center; font-size: 2.2em; }
#divc { border: 1px solid #555; }
.des { width: 500px; background-color: lightyellow;
border: 1px solid #555; padding: 25px; margin-top: 25px; }
.mouseover { color: #ffffff; background-color: highlight; width: 100%; cursor: default; }
.mouseout { color: #000; background-color: #ffffff; width: 100%; cursor: default; }
</style>
<script language="JavaScript">
function jsAuto(instanceName, objID) {
this._msg = []; // 候選資料
this._x = null; // 目前顯示的項目
this._o = document.getElementById(objID); // 提示容器
if (!this._o) return;
this._f = false; // 是否有符合的項目
this._i = instanceName; // 實例名稱
this._r = null; // 綁定的輸入框
this._c = 0; // 目前高亮的索引
this._s = false; // 是否已啟動鍵盤選擇
this._v = null; // 目前輸入值
this._o.style.visibility = "hidden";
this._o.style.position = "absolute";
this._o.style.zIndex = "9999";
this._o.style.overflow = "auto";
this._o.style.height = "50";
return this;
}
// 上下鍵與 Enter 的處理
jsAuto.prototype.directionKey = function () {
with (this) {
var e = _e.keyCode ? _e.keyCode : _e.which;
var l = _o.childNodes.length;
(_c > l - 1 || _c < 0) ? _s = false : "";
if (e == 40 && _s) { // 下
_o.childNodes[_c].className = "mouseout";
(_c >= l - 1) ? _c = 0 : _c++;
_o.childNodes[_c].className = "mouseover";
}
if (e == 38 && _s) { // 上
_o.childNodes[_c].className = "mouseout";
_c-- <= 0 ? _c = _o.childNodes.length - 1 : "";
_o.childNodes[_c].className = "mouseover";
}
if (e == 13) { // Enter
if (_o.childNodes[_c] && _o.style.visibility == "visible") {
_r.value = _x[_c];
_o.style.visibility = "hidden";
}
}
if (!_s) {
_c = 0;
_o.childNodes[_c].className = "mouseover";
_s = true;
}
}
};
// 滑鼠互動
jsAuto.prototype.domouseover = function (obj) {
with (this) {
_o.childNodes[_c].className = "mouseout";
_c = 0;
obj.tagName == "DIV" ? obj.className = "mouseover"
: obj.parentElement.className = "mouseover";
}
};
jsAuto.prototype.domouseout = function (obj) {
obj.tagName == "DIV" ? obj.className = "mouseout"
: obj.parentElement.className = "mouseout";
};
jsAuto.prototype.doclick = function (msg) {
with (this) {
if (_r) {
_r.value = msg;
_o.style.visibility = "hidden";
} else {
alert("javascript autocomplete ERROR : can not get return object.");
}
}
};
// 加入候選資料,以逗號分隔時會自動拆成多筆
jsAuto.prototype.item = function (msg) {
if (msg.indexOf(",") > 0) {
var arrMsg = msg.split(",");
for (var i = 0; i < arrMsg.length; i++) {
arrMsg[i] ? this._msg.push(arrMsg[i]) : "";
}
} else {
this._msg.push(msg);
}
this._msg.sort();
};
// 建立一個候選項目,並把輸入值高亮起來
jsAuto.prototype.append = function (msg) {
with (this) {
_i ? "" : _i = eval(_i);
_x.push(msg);
var div = document.createElement("DIV");
div.onmouseover = function () { _i.domouseover(this); };
div.onmouseout = function () { _i.domouseout(this); };
div.onclick = function () { _i.doclick(msg); };
var re = new RegExp("(" + _v + ")", "i");
div.style.lineHeight = "140%";
div.className = "mouseout";
if (_v) div.innerHTML = msg.replace(re, "<strong>$1</strong>");
div.style.fontFamily = "verdana";
_o.appendChild(div);
}
};
// 定位並顯示提示層
jsAuto.prototype.display = function () {
with (this) {
if (_f && _v !== "") {
_o.style.left = _r.offsetLeft;
_o.style.width = _r.offsetWidth;
_o.style.top = _r.offsetTop + _r.offsetHeight;
_o.style.visibility = "visible";
} else {
_o.style.visibility = "hidden";
}
}
};
// 主事件入口
jsAuto.prototype.handleEvent = function (fValue, fID, event) {
with (this) {
var re;
_e = event;
var e = _e.keyCode ? _e.keyCode : _e.which;
_x = [];
_f = false;
_r = document.getElementById(fID);
_v = fValue;
_i = eval(_i);
re = new RegExp("^" + fValue + "", "i");
_o.innerHTML = "";
for (var i = 0; i < _msg.length; i++) {
if (re.test(_msg[i])) {
_i.append(_msg[i]);
_f = true;
}
}
_i ? _i.display() : alert("can not get instance");
if (_f) {
if (e == 38 || e == 40 || e == 13) {
_i.directionKey();
} else {
_c = 0;
_o.childNodes[_c].className = "mouseover";
_s = true;
}
}
}
};
window.onerror = new Function("return true;");
// -->
</script>
<div id="divc"></div> <!-- 提示容器 -->
<div align="center">
<input id="auto" onkeyup="jsAutoInstance.handleEvent(this.value,'auto',event)">
</div>
<script language="JavaScript">
var jsAutoInstance = new jsAuto("jsAutoInstance", "divc");
jsAutoInstance.item("a-start,b-start,c-start,d-start,e-start,f-start,g-start");
jsAutoInstance.item("blueDestiny");
jsAutoInstance.item("BlueMiracle,Blue");
jsAutoInstance.item("angela,geniuslau");
jsAutoInstance.item("never-online");
</script>
<center>請在輸入框輸入一個字母:</center>
keyup,呼叫 handleEvent。^輸入值 的正則表達式篩出符合的候選,逐一 append 成 DIV。<strong> 把符合的字串包起來。display() 依輸入框的位置與寬度定位提示層並顯示。directionKey() 移動高亮,Enter 則把值寫回輸入框。(、*、+ 等字元,會讓 RegExp 構造失敗甚至引發錯誤,必須先 escape。with 在嚴格模式下被禁用,也容易讓 scope 混亂,改用 const self = this 或箭頭函式更清楚。textContent,再另外處理高亮。role="listbox"/aria-activedescendant 讓螢幕閱讀器能朗讀候選。