在输入字段上创建自动完成

创建于 2024-12-03 / 62
字体: [默认] [大] [更大]

了解如何创建 Autocomplete 自动完成功能。


自动完成

开始输入:


亲自试一试 »


创建自动填写表单

步骤 1) 添加 HTML:

实例

<!--确保表单已关闭自动完成功能:-->
<form autocomplete="off" action="/action_page.php">
  <div class="autocomplete" style="width:300px;">
    <input id="myInput" type="text" name="myCountry" placeholder="Country">
  </div>
  <input type="submit">
</form>

步骤 2) 创建一个 JavaScript 数组:

实例

世界上所有地区的数组:

var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua &amp; Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia &amp; Herzegovina","Botswana","Brazil","British Virgin Islands","Brunei","Bulgaria","Burkina Faso","Burundi","Cambodia","Cameroon","Canada","Cape Verde","Cayman Islands","Central Arfrican Republic","Chad","Chile","China","Colombia","Congo","Cook Islands","Costa Rica","Cote D Ivoire","Croatia","Cuba","Curacao","Cyprus","Czech Republic","Denmark","Djibouti","Dominica","Dominican Republic","Ecuador","Egypt","El Salvador","Equatorial Guinea","Eritrea","Estonia","Ethiopia","Falkland Islands","Faroe Islands","Fiji","Finland","France","French Polynesia","French West Indies","Gabon","Gambia","Georgia","Germany","Ghana","Gibraltar","Greece","Greenland","Grenada","Guam","Guatemala","Guernsey","Guinea","Guinea Bissau","Guyana","Haiti","Honduras","Hong Kong","Hungary","Iceland","India","Indonesia","Iran","Iraq","Ireland","Isle of Man","Israel","Italy","Jamaica","Japan","Jersey","Jordan","Kazakhstan","Kenya","Kiribati","Kosovo","Kuwait","Kyrgyzstan","Laos","Latvia","Lebanon","Lesotho","Liberia","Libya","Liechtenstein","Lithuania","Luxembourg","Macau","Macedonia","Madagascar","Malawi","Malaysia","Maldives","Mali","Malta","Marshall Islands","Mauritania","Mauritius","Mexico","Micronesia","Moldova","Monaco","Mongolia","Montenegro","Montserrat","Morocco","Mozambique","Myanmar","Namibia","Nauro","Nepal","Netherlands","Netherlands Antilles","New Caledonia","New Zealand","Nicaragua","Niger","Nigeria","North Korea","Norway","Oman","Pakistan","Palau","Palestine","Panama","Papua New Guinea","Paraguay","Peru","Philippines","Poland","Portugal","Puerto Rico","Qatar","Reunion","Romania","Russia","Rwanda","Saint Pierre &amp; Miquelon","Samoa","San Marino","Sao Tome and Principe","Saudi Arabia","Senegal","Serbia","Seychelles","Sierra Leone","Singapore","Slovakia","Slovenia","Solomon Islands","Somalia","South Africa","South Korea","South Sudan","Spain","Sri Lanka","St Kitts &amp; Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad &amp; Tobago","Tunisia","Turkey","Turkmenistan","Turks &amp; Caicos","Tuvalu","Uganda","Ukraine","United Arab Emirates","United Kingdom","United States of America","Uruguay","Uzbekistan","Vanuatu","Vatican City","Venezuela","Vietnam","Virgin Islands (US)","Yemen","Zambia","Zimbabwe"];

第 3 步)添加 CSS:

容器必须有 "relative" 定位。

实例

* { box-sizing: border-box; }
body {
  font: 16px Arial;
}
.autocomplete {
  /*容器必须相对定位:*/
  position: relative;
  display: inline-block;
}
input {
  border: 1px solid transparent;
  background-color: #f1f1f1;
  padding: 10px;
  font-size: 16px;
}
input[type=text] {
  background-color: #f1f1f1;
  width: 100%;
}
input[type=submit] {
  background-color: DodgerBlue;
  color: #fff;
}
.autocomplete-items {
  position: absolute;
  border: 1px solid #d4d4d4;
  border-bottom: none;
  border-top: none;
  z-index: 99;
  /*将自动完成项定位为与容器相同的宽度:*/
  top: 100%;
  left: 0;
  right: 0;
}
.autocomplete-items div {
  padding: 10px;
  cursor: pointer;
  background-color: #fff;
  border-bottom: 1px solid #d4d4d4;
}
.autocomplete-items div:hover {
  /*当悬停一个项目时:*/
  background-color: #e9e9e9;
}
.autocomplete-active {
  /*当使用箭头键浏览项目时:*/
  background-color: DodgerBlue !important;
  color: #ffffff;
}

第 4 步)添加 JavaScript:

实例

function autocomplete(inp, arr) {
  /* autocomplete 自动完成功能有两个参数,
  文本字段元素和一组可能的自动完成值:*/
  var currentFocus;
  /*当有人在文本字段中写入时执行一个函数:*/
  inp.addEventListener("input", function(e) {
      var a, b, i, val = this.value;
      /*关闭任何已经打开的自动完成值列表*/
      closeAllLists();
      if (!val) { return false;}
      currentFocus = -1;
      /*创建一个包含项目(值)的 DIV 元素:*/
      a = document.createElement("DIV");
      a.setAttribute("id", this.id + "autocomplete-list");
      a.setAttribute("class", "autocomplete-items");
      /*将 DIV 元素附加为自动完成容器的子元素:*/
      this.parentNode.appendChild(a);
      /*对于数组中的每一项...*/
      for (i = 0; i < arr.length; i++) {
        /*检查项目是否以与文本字段值相同的字母开头:*/
        if (arr[i].substr(0, val.length).toUpperCase() == val.toUpperCase()) {
          /*为每个匹配的元素创建一个DIV元素:*/
          b = document.createElement("DIV");
          /*将匹配的字母加粗:*/
          b.innerHTML = "<strong>" + arr[i].substr(0, val.length) + "</strong>";
          b.innerHTML += arr[i].substr(val.length);
          /*插入将保存当前数组项的值的输入字段:*/
          b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
          /*当有人点击项目值(DIV元素)时执行一个函数:*/
              b.addEventListener("click", function(e) {
              /*插入自动完成文本字段的值:*/
              inp.value = this.getElementsByTagName("input")[0].value;
              /*关闭自动完成值的列表,
              (或任何其他打开的自动完成值列表:*/
              closeAllLists();
          });
          a.appendChild(b);
        }
      }
  });
  /*执行一个函数按下键盘上的一个键:*/
  inp.addEventListener("keydown", function(e) {
      var x = document.getElementById(this.id + "autocomplete-list");
      if (x) x = x.getElementsByTagName("div");
      if (e.keyCode == 40) {
        /*如果按下箭头 DOWN 键,
        增加 currentFocus 变量:*/
        currentFocus++;
        /*并使当前项目更加可见:*/
        addActive(x);
      } else if (e.keyCode == 38) { //up
        /*如果按下向上箭头键,
        减少 currentFocus 变量:*/
        currentFocus--;
        /* 并使当前项目更明显:*/
        addActive(x);
      } else if (e.keyCode == 13) {
        /*如果按下 ENTER 键,则阻止提交表单,*/
        e.preventDefault();
        if (currentFocus > -1) {
          /*并模拟点击 "active" 项:*/
          if (x) x[currentFocus].click();
        }
      }
  });
  function addActive(x) {
    /*一个将项目分类为 "active" 的函数:*/
    if (!x) return false;
    /*首先删除所有项目的 "active" 类:*/
    removeActive(x);
    if (currentFocus >= x.length) currentFocus = 0;
    if (currentFocus < 0) currentFocus = (x.length - 1);
    /*添加类 "autocomplete-active":*/
    x[currentFocus].classList.add("autocomplete-active");
  }
  function removeActive(x) {
    /*从所有自动完成项中删除 "active" 类的函数:*/
    for (var i = 0; i < x.length; i++) {
      x[i].classList.remove("autocomplete-active");
    }
  }
  function closeAllLists(elmnt) {
    /*关闭文档中的所有自动完成列表,
    除了作为参数传递的那个:*/
    var x = document.getElementsByClassName("autocomplete-items");
    for (var i = 0; i < x.length; i++) {
      if (elmnt != x[i] && elmnt != inp) {
      x[i].parentNode.removeChild(x[i]);
    }
  }
}
/*当有人点击文档时执行一个函数:*/
document.addEventListener("click", function (e) {
    closeAllLists(e.target);
});
}
步骤 5) 在"myInput"上启动自动完成效果:

实例

将 countries 数组作为自动完成函数的第二个参数传递:

<script>
autocomplete(document.getElementById("myInput"), countries);
</script> 亲自试一试 »

0 人点赞过