How TO - Autocomplete
瞭解如何建立自動完成功能。
Autocomplete
開始輸入
建立自動完成表單
步驟 1) 新增 HTML
示例
<!--確保表單的 autocomplete 功能已關閉:-->
<form autocomplete="off" action="/action_page.php">
<div class="autocomplete" style="width:300px;">
<input id="myInput" type="text" name="myCountry" placeholder="國家">
</div>
<input type="submit">
</form>
步驟 2) 建立 JavaScript 陣列
示例
世界所有國家的陣列
var countries = ["Afghanistan","Albania","Algeria","Andorra","Angola","Anguilla","Antigua & Barbuda","Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan","Bahamas","Bahrain","Bangladesh","Barbados","Belarus","Belgium","Belize","Benin","Bermuda","Bhutan","Bolivia","Bosnia & 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 & 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 & Nevis","St Lucia","St Vincent","Sudan","Suriname","Swaziland","Sweden","Switzerland","Syria","Taiwan","Tajikistan","Tanzania","Thailand","Timor L'Este","Togo","Tonga","Trinidad & Tobago","Tunisia","Turkey","Turkmenistan","Turks & 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
容器必須具有“相對”定位。
示例
* { 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) {
/*此自動完成函式接受兩個引數,
文字欄位元素和一個可能的自動完成值的陣列:*/
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);
/*插入一個 input 欄位,其中將儲存當前陣列項的值:*/
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
/*如果按下箭頭 UP 鍵,
則減少 currentFocus 變數:*/
currentFocus--;
/*並使當前專案更加可見:*/
addActive(x);
} else if (e.keyCode == 13) {
/*如果按下 ENTER 鍵,則阻止表單提交,*/
e.preventDefault();
if (currentFocus > -1) {
/*然後模擬單擊“活動”專案:*/
if (x) x[currentFocus].click();
}
}
});
function addActive(x) {
/*一個將專案分類為“活動”的函式:*/
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 陣列作為 autocomplete 函式的第二個引數傳遞
<script>
autocomplete(document.getElementById("myInput"), countries);
</script>
自己動手試一試 »