DIV CSS 佈局教程網

仿百度搜尋的 jQuery 自動補全:鍵盤上下鍵選擇也能用
編輯:關於JavaScript     

自動補全是搜尋框的標配。這個版本不依賴任何外掛,用原生 JS 封裝成一個 AutoComplete 建構函式,支援:輸入即過濾、命中字串粗體、滑鼠移入高亮、上下鍵切換、Enter 確認、視窗縮放時重新定位。

<!doctype html>
<html>
<meta charset="utf-8">
<style>
body { margin: 0; }
.auto_hidden {
  width: 204px; border: 1px solid #333; position: absolute; display: none;
}
.auto_show {
  width: 204px; border: 1px solid #333; position: absolute; z-index: 9999; display: block;
}
.auto_onmouseover { color: #ffffff; background-color: highlight; width: 100%; }
.auto_onmouseout  { color: #000000; width: 100%; background-color: #ffffff; }
</style>

<script language="javascript">
var $ = function (id) {
  return "string" == typeof id ? document.getElementById(id) : id;
};
var Bind = function (object, fun) {
  return function () { return fun.apply(object, arguments); };
};

function AutoComplete(obj, autoObj, arr) {
  this.obj = $(obj);            // 輸入框
  this.autoObj = $(autoObj);    // 提示層
  this.value_arr = arr;         // 建議字串陣列,不可含重複值
  this.index = -1;              // 目前高亮的索引
  this.search_value = "";       // 保存當前輸入的內容
}

AutoComplete.prototype = {
  // 讓提示層對齊輸入框
  init: function () {
    this.autoObj.style.left = this.obj.offsetLeft + "px";
    this.autoObj.style.top = this.obj.offsetTop + this.obj.offsetHeight + "px";
    this.autoObj.style.width = this.obj.offsetWidth - 2 + "px"; // 扣掉邊框 2px
  },

  deleteDIV: function () {
    while (this.autoObj.hasChildNodes()) {
      this.autoObj.removeChild(this.autoObj.firstChild);
    }
    this.autoObj.className = "auto_hidden";
  },

  // 點選某筆:把值寫回輸入框並收起提示層
  setValue: function (_this) {
    return function () {
      _this.obj.value = this.seq;
      _this.autoObj.className = "auto_hidden";
    };
  },

  autoOnmouseover: function (_this, _div_index) {
    return function () {
      _this.index = _div_index;
      var length = _this.autoObj.children.length;
      for (var j = 0; j < length; j++) {
        _this.autoObj.childNodes[j].className =
          (j != _this.index) ? 'auto_onmouseout' : 'auto_onmouseover';
      }
    };
  },

  // 依目前 index 更新所有項目的樣式與輸入框的值
  changeClassname: function (length) {
    for (var i = 0; i < length; i++) {
      if (i != this.index) {
        this.autoObj.childNodes[i].className = 'auto_onmouseout';
      } else {
        this.autoObj.childNodes[i].className = 'auto_onmouseover';
        this.obj.value = this.autoObj.childNodes[i].seq;
      }
    }
  },

  // 鍵盤操作:40 下、38 上、13 確認
  pressKey: function (event) {
    var length = this.autoObj.children.length;
    if (event.keyCode == 40) {            // ↓
      ++this.index;
      if (this.index > length) { this.index = 0; }
      else if (this.index == length) { this.obj.value = this.search_value; }
      this.changeClassname(length);
    } else if (event.keyCode == 38) {     // ↑
      this.index--;
      if (this.index < -1) { this.index = length - 1; }
      else if (this.index == -1) { this.obj.value = this.search_value; }
      this.changeClassname(length);
    } else if (event.keyCode == 13) {     // Enter
      this.autoObj.className = "auto_hidden";
      this.index = -1;
    } else {
      this.index = -1;
    }
  },

  start: function (event) {
    if (event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40) {
      this.init();
      this.deleteDIV();
      this.search_value = this.obj.value;
      var valueArr = this.value_arr;
      valueArr.sort();
      if (this.obj.value.replace(/(^\s*)|(\s*$)/g, '') == "") { return; }
      var reg;
      try { reg = new RegExp("(" + this.obj.value + ")", "i"); }
      catch (e) { return; }

      var div_index = 0;
      for (var i = 0; i < valueArr.length; i++) {
        if (reg.test(valueArr[i])) {
          var div = document.createElement("div");
          div.className = "auto_onmouseout";
          div.seq = valueArr[i];
          div.onclick = this.setValue(this);
          div.onmouseover = this.autoOnmouseover(this, div_index);
          // 命中的字串粗體顯示
          div.innerHTML = valueArr[i].replace(reg, "<strong>$1</strong>");
          this.autoObj.appendChild(div);
          this.autoObj.className = "auto_show";
          div_index++;
        }
      }
    }
    this.pressKey(event);
    // 視窗尺寸改變時重新對齊
    window.onresize = Bind(this, function () { this.init(); });
  }
};
</script>

<body>
<div align="center" style="padding-top:50px">
  <input type="text" style="width:300px; height:20px; font-size:14pt;"
    placeholder="請輸入 a 或 b 模擬效果" id="o" onkeyup="autoComplete.start(event)">
</div>
<div class="auto_hidden" id="auto"></div>
<script>
var autoComplete = new AutoComplete('o', 'auto',
  ['b0','b12','b22','b3','b4','b5','b6','b7','b8','b2',
   'abd','ab','acd','accd','b1','cd','ccd','cbcv','cxf']);
</script>
</body>
</html>

幾個值得學的細節:setValue 與 autoOnmouseover 都回傳一個閉包,把 this 與索引提前綁好,避免迴圈裡的 this 指向錯誤;replace(reg, "<strong>$1</strong>") 用捕獲組把命中片段包起來,做出百度那種粗體效果;pressKey 在選到頭尾之外時會把值還原成 search_value,使用者按鍵盤瀏覽後不會誤留一個不完整的字。

要接真實資料,只要把 value_arr 換成 Ajax 回傳的陣列即可。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved