微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

原生js编写autoComplete插件

最近有提关于下拉选项过多的时候,希望输入关键词,可以搜索内容的需求,但是之前项目太赶,所以也就没有来得及做,因为希望用原生js写一些内容,所以插件是采用了原生js写的思路如下

第一步:

fnInit实现初始化一些字段

第二步:

加载搜索框的div

第三步:

实现search功能删除原节点并加载新节点

第四步:

点击或者回车的时候设置value 代码: autoComplete.js

function AutoComplete() {
if (!(this instanceof AutoComplete)) {
return new AutoComplete();
}
this.sSearchValue = '';
this.index = -1;
}

AutoComplete.prototype = {
fnInit: function (option) {//初始化基本信息
var oDefault = {
id: '',//控件id
data: [],//数据
paraName: '',textFiled: '',//显示的文字的属性名
valueFiled: '',//获取value的属性名
style: {},//显示的下拉div的样式设置
url: '',//ajax请求的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();//加载选项额divid 

  //判断如果传入了url,没有传入data数据,就ajax获取数据,否则使用data取数据 
  if (this.sUrl !== '' && this.aData.length === 0) { 
    var that = this; 
    this.util.fnGet(this.sUrl,function (data) { 
      console.log(eval(data)); 
      that.aData = eval(data); 
    },10); 
  } 

  //给aData排序 
  var sTextField = this.sTextFiled; 
  this.aData.sort(function (a,b) { 
    return a[sTextField] > b[sTextField]; 
  }); 
  //<a href="https://www.jb51.cc/tag/huoqu/" target="_blank" class="keywords">获取</a>控件 
  this.domInput = document.getElementById(this.sId); 
  //this.domDiv = document.getElementById(this.sDivId); 
},fnRender: function () {//渲染一些必须的节点 
  var that = this; 
  //<a href="https://www.jb51.cc/tag/shengcheng/" target="_blank" class="keywords">生成</a><a href="https://www.jb51.cc/tag/yige/" target="_blank" class="keywords">一个</a>对应的div,承载后面的一些选项的 
  if (that.sDivId) { 
    var domDiv = document.createElement('div'); 
    domDiv.id = that.sDivId; 
    domDiv.style.background = '#fff'; 
    domDiv.style.width = that.domInput.offsetWidth - 2 + 'px'; 
    domDiv.style.position = 'absolute'; 
    domDiv.style.border = '1px solid #a9a9a9'; 
    domDiv.style.<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>play = 'none'; 
    that.util.fnInsertAfter(domDiv,that.domInput); 

    //加载之后才能将domDiv赋值为 
    this.domDiv = document.getElementById(this.sDivId); 
  } 
  //给input<a href="https://www.jb51.cc/tag/tianjia/" target="_blank" class="keywords">添加</a>keyup事件 
  that.util.fnAddEvent(that.domInput,'keyup',function (event) { 
    that.fnSearch(event); 
  }); 
},fnSearch: function (event) { 
  //判断如果不是回车键,上键下键的时候执行<a href="https://www.jb51.cc/tag/sousuo/" target="_blank" class="keywords">搜索</a> 
  if (event.keyCode != 13 && event.keyCode != 38 && event.keyCode != 40) { 
    this.fnLoadSearchContent(); 
    this.fnShowDiv(); 
  } else {//<a href="https://www.jb51.cc/tag/sousuo/" target="_blank" class="keywords">搜索</a>之后监测<a href="https://www.jb51.cc/tag/jianpan/" target="_blank" class="keywords">键盘</a>事件 
    var length = this.domDiv.children.length; 
    if (event.keyCode == 40) { 
      ++this.index; 
      if (this.index >= length) { 
        this.index = 0; 
      } else if (this.index == length) { 
        this.domInput.value = this.sSearchValue; 
      } 
      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; 
      } else if (this.index == -1) { 
        this.obj.value = this.sSearchValue; 
      } 
      this.domInput.value = this.domDiv.childNodes[this.index].text; 
      this.fnChangeClass(); 
    } 
    else if (event.keyCode == 13) { 
      this.fnLoadSearchContent(); 
      this.fnShowDiv(); 
      //this.domDiv.style.<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>play = this.domDiv.style.<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>play === 'none' ? 'block' : 'none'; 
      this.index = -1; 
    } else { 
      this.index = -1; 
    } 
  } 
},fnLoadSearchContent: function () { 
  //<a href="https://www.jb51.cc/tag/shanchu/" target="_blank" class="keywords">删除</a>所有的子节点 
  while (this.domDiv.hasChildNodes()) { 
    this.domDiv.removeChild(this.domDiv.f<a href="https://www.jb51.cc/tag/irs/" target="_blank" class="keywords">irs</a>tChild); 
  } 
  //设置search的值 
  this.sSearchValue = this.domInput.value; 
  //如果值为空的时候选择<a href="https://www.jb51.cc/tag/tuichu/" target="_blank" class="keywords">退出</a> 
  var sTr<a href="https://www.jb51.cc/tag/ims/" target="_blank" class="keywords">ims</a>earchValue = this.sSearchValue.replace(/(^\s*)|(\s*$)/g,''); 
  if (sTr<a href="https://www.jb51.cc/tag/ims/" target="_blank" class="keywords">ims</a>earchValue == "") { 
    this.domDiv.style.<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>play = 'none'; 
    return; 
  } 
  try { 
    var reg = new RegExp("(" + sTr<a href="https://www.jb51.cc/tag/ims/" target="_blank" class="keywords">ims</a>earchValue + ")","i"); 
  } 
  catch (e) { 
    return; 
  } 
  //<a href="https://www.jb51.cc/tag/sousuo/" target="_blank" class="keywords">搜索</a>并<a href="https://www.jb51.cc/tag/zengjia/" target="_blank" class="keywords">增加</a>新节点 
  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"); 
      //div.className="auto_onmou<a href="https://www.jb51.cc/tag/SEO/" title="SEO">SEO</a>ut"; 
      domDiv.text = this.aData[i][this.sTextFiled]; 
      domDiv.onclick = this.fnSetValue(this); 
      domDiv.onmou<a href="https://www.jb51.cc/tag/SEO/" title="SEO">SEO</a>ver = this.fnAutoOnMou<a href="https://www.jb51.cc/tag/SEO/" title="SEO">SEO</a>ver(this,nDivIndex); 
      domDiv.innerHTML = this.aData[i][this.sTextFiled].replace(reg,"<h3>$1</h3>");//<a href="https://www.jb51.cc/tag/sousuo/" target="_blank" class="keywords">搜索</a>到的字符粗体<a href="https://www.jb51.cc/tag/xianshi/" target="_blank" class="keywords">显示</a> 
      this.domDiv.appendChild(domDiv); 
      nDivIndex++; 
    } 
  } 
},fnSetValue: function (that) { 
  return function () { 
    that.domInput.value = this.text; 
    that.domDiv.style.<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>play = 'none'; 
  } 
},fnAutoOnMou<a href="https://www.jb51.cc/tag/SEO/" title="SEO">SEO</a>ver: 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 = ''; 
      that.domDiv.childNodes[j].style.color = '#000'; 
    } else { 
      that.domDiv.childNodes[j].style.backgroundColor = 'blue'; 
      that.domDiv.childNodes[j].style.color = '#fff'; 
    } 
  } 
},fnShowDiv: function () { 
  if (this.domDiv.children.length !== 0) { 
    this.domDiv.style.<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>play = this.domDiv.style.<a href="https://www.jb51.cc/tag/dis/" target="_blank" class="keywords">dis</a>play === 'none' ? 'block' : 'none'; 
  } 
},util: {//公共接口<a href="https://www.jb51.cc/tag/fangfa/" target="_blank" class="keywords">方法</a> 
  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 if (document.attachEvent) { 
      ele.attachEvent('on' + (evt == "input" ? "propertychange" : evt),fn); 
    } else { 
      ele['on' + (evt == "input" ? "propertychange" : evt)] = fn; 
    } 
  },fnGet: function (url,timeout) { 
    var xhr = null; 
    try { 
      if (window.XMLHttpRequest) { 
        xhr = new XMLHttpRequest(); 
      } else if (Window.ActiveXObject) { 

        xhr = new ActiveXObject("Msxml2.Xmlhttp"); 
      } 
    } catch (e) { 
      //T<a href="https://www.jb51.cc/tag/odo/" target="_blank" class="keywords">odo</a> handle the exception 
      xhr = new ActiveXObject('Microsoft.Xmlhttp'); 
    } 
    xhr.onreadystatechange = function () { 
      if (this.readyState == 4 && this.status == 200) { 
        fn.call(this,this.responseText); 
      } else { 
        setTimeout(function () { 
          xhr.abort(); 
        },timeout); 
      } 
    }; 
    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

rush:xhtml;"> <Meta charset="UTF-8"> Title

<script src="autoComplete.js">

data.json

rush:js;"> [ { "id": "1","name": "aaaaa" },{ "id": "2","name": "bbbbb" },{ "id": "3","name": "ccccc" } ]

以上就是本文的全部内容,希望对大家学习javascript程序设计有所帮助。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐