DIV CSS 佈局教程網

用原生 JS 打造 autoComplete 自動完成下拉插件
編輯:關於JavaScript     

最近遇到一個需求:當下拉選項數量特別多時,希望能透過輸入關鍵字快速過濾出想要的內容。由於之前項目排期太緊一直沒顧上,這次正好有機會動手,而且我希望用純原生 JavaScript 來實現,不依賴任何類庫。整體思路可以拆成四步:

第一步:由 fnInit 完成初始化,設定各項配置欄位。

第二步:動態建立承載搜索框的容器節點。

第三步:實作 search 功能,刪除舊節點並渲染新節點。

第四步:在使用者點擊或按下回車時,把選中項寫回輸入框。

下面是 autoComplete.js 的完整程式碼:

(function () {
  function AutoComplete() {
    if (!(this instanceof AutoComplete)) { return new AutoComplete(); }
    this.sSearchValue = '';
    this.index = -1;
  }
  AutoComplete.prototype = {
    fnInit: function (option) {//初始化基本設定
      var oDefault = { id: '', data: [], paraName: '', textFiled: '', valueFiled: '', style: {}, url: '', select: function () { } };
      var _option = option;
      this.sId = _option.id || oDefault.id;
      this.aData = _option.data || oDefault.data;
      this.paraName = _option.paraName || oDefault.paraName;
      this.sTextFiled = _option.textFiled || oDefault.textFiled;
      this.sValueFiled = _option.valueFiled || oDefault.valueFiled;
      this.style = _option.style || oDefault.style;
      this.sUrl = _option.url || oDefault.url;
      this.fnSelect = _option.select || oDefault.select;
      this.sDivId = this.sId + new Date().getTime();
      if (this.sUrl !== '' && this.aData.length === 0) {
        var that = this;
        this.util.fnGet(this.sUrl, function (data) { that.aData = eval(data); }, 10);
      }
      var sTextField = this.sTextFiled;
      this.aData.sort(function (a, b) { return a[sTextField] > b[sTextField]; });
      this.domInput = document.getElementById(this.sId);
    },
    fnRender: function () {//渲染必要節點
      var that = this;
      if (that.sDivId) {
        var domDiv = document.createElement('div');
        domDiv.id = that.sDivId;
        domDiv.style.position = 'absolute';
        domDiv.style.display = 'none';
        that.util.fnInsertAfter(domDiv, that.domInput);
        this.domDiv = document.getElementById(this.sDivId);
      }
      that.util.fnAddEvent(that.domInput, 'keyup', function (event) { that.fnSearch(event); });
    },
    fnSearch: function (event) {
      if (event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40) {
        this.fnLoadSearchContent(); this.fnShowDiv();
      } else {
        var length = this.domDiv.children.length;
        if (event.keyCode == 40) {
          ++this.index;
          if (this.index >= length) { this.index = 0; }
          this.domInput.value = this.domDiv.childNodes[this.index].text;
          this.fnChangeClass();
        } else if (event.keyCode == 38) {
          this.index--;
          if (this.index <= -1) { this.index = length - 1; }
          this.domInput.value = this.domDiv.childNodes[this.index].text;
          this.fnChangeClass();
        } else if (event.keyCode == 13) {
          this.fnLoadSearchContent(); this.fnShowDiv(); this.index = -1;
        }
      }
    },
    fnLoadSearchContent: function () {
      while (this.domDiv.hasChildNodes()) { this.domDiv.removeChild(this.domDiv.firstChild); }
      this.sSearchValue = this.domInput.value;
      var sTrimSearchValue = this.sSearchValue.replace(/(^\s*)|(\s*$)/g, '');
      if (sTrimSearchValue == "") { this.domDiv.style.display = 'none'; return; }
      try { var reg = new RegExp("(" + sTrimSearchValue + ")", "i"); } catch (e) { return; }
      var nDivIndex = 0;
      for (var i = 0; i < this.aData.length; i++) {
        if (reg.test(this.aData[i][this.sTextFiled])) {
          var domDiv = document.createElement("div");
          domDiv.text = this.aData[i][this.sTextFiled];
          domDiv.onclick = this.fnSetValue(this);
          domDiv.onmouseover = this.fnAutoOnMouseOver(this, nDivIndex);
          domDiv.innerHTML = this.aData[i][this.sTextFiled].replace(reg, "<strong>$1</strong>");
          this.domDiv.appendChild(domDiv); nDivIndex++;
        }
      }
    },
    fnSetValue: function (that) { return function () { that.domInput.value = this.text; that.domDiv.style.display = 'none'; } },
    fnAutoOnMouseOver: function (that, idx) { return function () { that.index = idx; that.fnChangeClass(); } },
    fnChangeClass: function () {
      var that = this; var length = that.domDiv.children.length;
      for (var j = 0; j < length; j++) {
        if (j != that.index) { that.domDiv.childNodes[j].style.backgroundColor = ''; }
        else { that.domDiv.childNodes[j].style.backgroundColor = 'blue'; }
      }
    },
    fnShowDiv: function () {
      if (this.domDiv.children.length !== 0) { this.domDiv.style.display = this.domDiv.style.display === 'none' ? 'block' : 'none'; }
    },
    util: {
      fnInsertAfter: function (ele, targetEle) {
        var parentnode = targetEle.parentNode || targetEle.parentElement;
        if (parentnode.lastChild == targetEle) { parentnode.appendChild(ele); }
        else { parentnode.insertBefore(ele, targetEle.nextSibling); }
      },
      fnAddEvent: function (ele, evt, fn) {
        if (document.addEventListener) { ele.addEventListener(evt, fn, false); }
        else { ele['on' + evt] = fn; }
      },
      fnGet: function (url, fn, timeout) {
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function () { if (this.readyState == 4 && this.status == 200) { fn.call(this, this.responseText); } };
        xhr.open('get', url, true); xhr.send();
      }
    }
  }
  window.AutoComplete = function (option) {
    var aOption = Array.prototype.slice.call(arguments);
    for (var i = 0; i < aOption.length; i++) {
      var autoComplete = new AutoComplete();
      autoComplete.fnInit(aOption[i]); autoComplete.fnRender();
    }
  }
})(window);

頁面調用示例(index.html):

<div><input type="text" id="txtTest"></div>
<div><input type="text" id="txtTest1"></div>
<script>
window.onload = function () {
  var option = { id: 'txtTest', data: [{ "id": "1", "name": "aaaaa" }, { "id": "2", "name": "bbbbb" }], textFiled: 'name', valueFiled: 'id', select: function (val, text) { alert(val + text); } };
  var option1 = { id: 'txtTest1', url: 'data.json', textFiled: 'name', valueFiled: 'id' };
  AutoComplete(option, option1);
};
</script>

對應的 data.json:

[ { "id": "1", "name": "aaaaa" }, { "id": "2", "name": "bbbbb" }, { "id": "3", "name": "ccccc" } ]

以上就是這個原生 autoComplete 插件的完整實作,支援鍵盤上下鍵、回車以及滑鼠點擊選取,希望對學習 JavaScript 的朋友有所幫助。

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