功能特點
- 輸入字元即時過濾建議清單
- 鍵盤上下鍵選擇、Enter 確認
- 滑鼠點擊選項填入
- 關鍵字高亮顯示
- 靜態資料來源,可擴充為 AJAX 動態載入
核心類別 jsAuto
function jsAuto(instanceName, containerId) {
this._msg = []; // 建議資料陣列
this._o = document.getElementById(containerId); // 建議容器
this._i = instanceName; // 實例名稱(供事件回呼用)
this._v = null; // 當前輸入值
this._c = 0; // 目前高亮索引
this._s = false; // 是否顯示中
// 樣式初始化
this._o.style.cssText = "visibility:hidden;position:absolute;z-index:9999;overflow:auto;height:50px";
return this;
}
關鍵方法
| 方法 | 功能 |
| item(msg) | 加入建議資料,支援逗號分隔多筆,自動排序 |
| append(msg) | 建立 DIV 元素、綁定滑鼠事件、關鍵字高亮、加入容器 |
| display() | 定位容器至輸入框下方、顯示/隱藏 |
| handleEvent(value, inputId, event) | 核心處理:過濾資料、重建清單、鍵盤導航 |
| directionKey() | 上下鍵切換高亮、Enter 填入 |
| domouseover/out/click | 滑鼠互動事件 |
使用方式
<div id="divc"></div> <!-- 建議容器 -->
<input onkeyup="jsAutoInstance.handleEvent(this.value,'auto',event)" id="auto">
<script>
var jsAutoInstance = new jsAuto("jsAutoInstance", "divc");
jsAutoInstance.item("a-start,b-start,c-start,..."); // 大量測試資料
jsAutoInstance.item("blueDestiny");
jsAutoInstance.item("BlueMiracle,Blue");
jsAutoInstance.item("angela,geniuslau");
jsAutoInstance.item("never-online");
</script>
擴充為 AJAX 版本
// 在 handleEvent 中改為非同步請求
handleEvent: function(value, inputId, event) {
if (value.length < 2) { this._o.style.visibility = "hidden"; return; }
$.getJSON("/api/suggest", { q: value }, function(data) {
this._msg = data.suggestions;
this._x = [];
this._o.innerHTML = "";
data.suggestions.forEach(function(item) { this.append(item); }, this);
this.display();
}.bind(this));
}