autocomplete.js

这是一个关于如何使用javascript实现自动补全功能的代码示例。通过AutoComplete函数,可以为输入框添加自动补全功能,根据用户输入的内容动态过滤数据,并显示匹配项。示例中展示了如何处理数据、创建补全面板、根据用户按键行为进行操作等核心功能。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 <html>
 <head>
  <script>
/**
 * autocomplete ??
 * ?????IE 6
 * @param textField            ????
 * @param valueField           ???
 * @param data                 ????
 * @param showField            ??????????????key
 * @param comparedField        ??????????????key
 * @param comparedValueField   ????????????key
 * @param filterField          ????????????key
 * @param filterValue          ??????
 * @return
 * @author ex-hantao001
 */
function AutoComplete(textField, valueField, data, showField, comparedField, comparedValueField, filterField, filterValue){
    this.textField = typeof(textField) == "object"?textField:document.getElementById(textField);
    this.valueField = typeof(valueField) == "object"?valueField:document.getElementById(valueField);
    this.tempData = null;
    this.dataPanel = null;
    this.data = data;  
    this.filterField = filterField;
    this.tilterValue = filterValue;
    this.showField = showField;
    this.comparedField = comparedField;
    this.comparedValueField = comparedValueField;
    this.selectedIndex = -1;
    this.init();
}
/**
 *???
 */
AutoComplete.prototype.init = function(){
 this.selectedIndex = -1;
    if(this.textField == null || this.data == null){
     return;
 }
 if(this.filterField != null)this.data = this.filter(this.data, this.filterField, this.filterValue);
 this.createPanel();
    var autoComplete = this;
    autoComplete.compare(this.comparedField, this.comparedValueField);
  
    this.textField.onkeyup = function(){
        autoComplete.compare(autoComplete.comparedField, autoComplete.comparedValueField);
         //up 38 down 40
        if(event.keyCode == 40){
         var table = document.getElementById("container");      
         if(autoComplete.selectedIndex+1 < table.rows.length){
          autoComplete.selectedIndex++;
          table.rows[autoComplete.selectedIndex].cells[0].style.backgroundColor = "yellow";
         }
        }else if(event.keyCode == 38){
         var table = document.getElementById("container");
         if(autoComplete.selectedIndex - 1 > -1 ) {
          autoComplete.selectedIndex--;
          table.rows[autoComplete.selectedIndex].cells[0].style.backgroundColor = "yellow";
         }
        }      
    }
   
    // ??? ?????????????????
    document.onkeydown = function(){
     var table = document.getElementById("container");      
     if(event.keyCode == 13){
         autoComplete.valueField.value = table.rows[autoComplete.selectedIndex].cells[0].getAttribute(autoComplete.comparedValueField);
         autoComplete.valueField.focus();
         document.getElementById("dataPanel").style.height = 0;
         event.keyCode = 0;
         event.returnValue = "return false";
         event.cancelBubble = true;
         return false;
        }
        if(event.keyCode == 27){
         document.getElementById("dataPanel").style.display = "none";
        }
    }  
   
}

/*
 * ??
 */
 AutoComplete.prototype.filter = function(data, field, value){
    var newArray = [];
    for(var i = 0; i < data.length; i++) {
      if(data[i][field].trim() == value){
          newArray.push(data[i]);
      }
    }
    return newArray;
 }


/*
 * ?????????
 */
AutoComplete.prototype.getXy = function(targetObj){
    var field = targetObj;
    if(!field){
        alert("???????");
        return;
    }
   
    var _offX = field.offsetLeft;
    var _offY = field.offsetTop;
   
    var obj = field;
   
    while(obj = obj.offsetParent){
        _offX += obj.offsetLeft;
        _offY += obj.offsetTop;
    }
    _offY += field.offsetHeight+2;
    return {x:_offX ,y:_offY};
   
}

/*
 * ??????
 */
AutoComplete.prototype.createPanel = function() {
 if(document.getElementById("dataPanel") != null) {
       document.getElementById("dataPanel").style.display = "block";
       document.getElementById("dataPanel").style.top = 0;
       document.getElementById("dataPanel").style.left = 0;
       return;
 }
    this.dataPanel = document.createElement("div");
    this.dataPanel.id = "dataPanel";
    this.dataPanel.style.cssText = "width:150px; height:300px; overflow-y:auto; position:absolute; top:0px; left:0px; background:red";
    document.body.appendChild(this.dataPanel);
    var container = document.createElement("table");
    container.id = "container";
    container.width = "100%";
    this.dataPanel.appendChild(container);
}

/*
 * ??
 */
AutoComplete.prototype.compare = function(f, v){
    var _x = this.getXy(this.textField).x + 150 > parseInt(document.body.scrollWidth) ? this.getXy(this.textField).x - (150 - parseInt(this.textField.offsetWidth)) : this.getXy(this.textField).x;
    var _y = this.getXy(this.textField).y;
    document.getElementById("dataPanel").style.left = _x;
    document.getElementById("dataPanel").style.top = _y;
    var arr = this.data;
    this.tempData = [];
    var isExist = false;
    var tbl = document.getElementById("container");
    for(var i = tbl.rows.length-1; i >= 0 ; i--){
     tbl.deleteRow(i);
    }
  
    for(var i = 0; i < arr.length; i++){
        if(arr[i][f].trim().length > this.textField.value.trim().length && arr[i][f].indexOf(this.textField.value.trim()) == 0) {
            this.append(arr[i],this.showField,v);
            isExist = true;
        }
    }
    document.getElementById("dataPanel").style.height = document.getElementById("container").offsetHeight
    if(!isExist) document.getElementById("dataPanel").style.height = 0;
}

/*
 * ??????
 */
AutoComplete.prototype.append = function(data, textName, valueName){
    if(!data)return; 
    var autoComplete = this;
    for(var i = 0; i < this.tempData.length; i++){
     if(data[valueName] == this.tempData[i][valueName]) {
         return;
     }
       
    }
   
    var tbl = document.getElementById("container");
    tbl.style.cssText = "background-color:#FFF;";
    tbl.width = "100%";
    var row = tbl.insertRow(-1);
    var cell = row.insertCell(-1);
    cell.width = "100%"
   
    cell.style.cssText = row.rowIndex%2 == 1 ? "background-color:#EEE;border-bottom:1px dashed #EEE;":"background-color:#FFF; border-bottom:1px dashed #EEE;";
    cell.onmouseover = function(){
     for(var i = 0; i < tbl.rows.length; i++){
      var td = tbl.rows[i].cells[0];
      td.style.backgroundColor = i%2 == 1 ? "#EEE" : "#FFF";
     }
        this.style.cursor = "pointer";
        this.style.backgroundColor = "yellow";
        autoComplete.selectedIndex = this.parentNode.rowIndex;
    }
    cell.onmouseout = function(){
        this.style.cursor = "default";
        this.style.backgroundColor = row.rowIndex%2 == 1 ? "#EEE" : "#FFF";
    }
  
    cell.onmousedown = function(){
       autoComplete.textField.value = data[textName];
       if(valueName != null && data[valueName] != null)
       if(autoComplete.valueField)autoComplete.valueField.value = data[valueName];
       document.getElementById("dataPanel").style.display = "none";
    }  
    cell.setAttribute(valueName,data[valueName]);
    cell.innerHTML = data[textName];
    this.tempData.push(data);
    if(parseInt(tbl.offsetHeight) > 300){
     document.getElementById("dataPanel").style.border = "1px solid #000";
     tbl.style.border = "0px";
    }else{
     document.getElementById("dataPanel").style.border = "0";
     tbl.style.border = "1px solid #000";   
    }
   
}

/*
 * ????????
 */
AutoComplete.prototype.getValueOfText = function(data, text, comparedField, comparedValueField) {
    if(!data) return;
    for(var i = 0; i < data.length; i++) {
        if(data[i][comparedField] == text)return data[i][comparedValueField];   
    }
}

String.prototype.trim = function(){
 return this.replace(/^/s+|/s+$/g,this);
}


function debug(s){
    document.body.insertAdjacentHTML("BeforeEnd","debug:"+s+"<br>");
}


var datas = [
   {"a":'??1 | 001',b:'001',c:"a"},
   {"a":'??2 | 002',b:'002',c:"a"},
   {"a":'??3 | 003',b:'003',c:"a"},
   {"a":'??4 | 004',b:'004',c:"a"},
   {"a":'??1 | 1001',b:'1001',c:"b"},
   {"a":'??2 | 1002',b:'1002',c:"b"},
   {"a":'??3 | 1003',b:'1003',c:"b"}
  
];

String.prototype.trim = function(){
 return this.replace(/^/s+|/s+$/g,this);
}


function debug(s){
    document.body.insertAdjacentHTML("BeforeEnd","debug:"+s+"<br>");
}

var ac = new AutoComplete();
function aa(obj) {
   ac.textField= obj
   ac.valueField = obj
   ac.data = datas;
   ac.showField = "a";
   ac.comparedField = "b";
   ac.comparedValueField = "b";
   ac.filterField = "c";
   ac.filterValue = "a";
   ac.init();
}

 

 

</script>
</head>
<body>
  <form name="f1">
  <input type="text" id="no1" value="" onfocus="aa(this)" />
  <input type="text" name="val" />
 </form>
</body>
</html>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值