JS实现联想、自动补齐国家或地区名称的功能


Posted in Javascript onJuly 07, 2020

1.JS部分

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;
   /*创建列表*/
   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);
     /*insert a input field that will hold the current array item's value:*/
     b.innerHTML += "<input type='hidden' value='" + arr[i] + "'>";
     /*execute a function when someone clicks on the item value (DIV element):*/
     b.addEventListener("click", function(e) {
       /*insert the value for the autocomplete text field:*/
       inp.value = this.getElementsByTagName("input")[0].value;
       /*close the list of autocompleted values,
       (or any other open lists of autocompleted values:*/
       closeAllLists();
     });
     a.appendChild(b);
    }
   }
 });
 /*execute a function presses a key on the keyboard:*/
 inp.addEventListener("keydown", function(e) {
   var x = document.getElementById(this.id + "autocomplete-list");
   if (x) x = x.getElementsByTagName("div");
   if (e.keyCode == 40) {
    /*If the arrow DOWN key is pressed,
    increase the currentFocus variable:*/
    currentFocus++;
    /*and and make the current item more visible:*/
    addActive(x);
   } else if (e.keyCode == 38) { //up
    /*If the arrow UP key is pressed,
    decrease the currentFocus variable:*/
    currentFocus--;
    /*and and make the current item more visible:*/
    addActive(x);
   } else if (e.keyCode == 13) {
    /*If the ENTER key is pressed, prevent the form from being submitted,*/
    e.preventDefault();
    if (currentFocus > -1) {
     /*and simulate a click on the "active" item:*/
     if (x) x[currentFocus].click();
    }
   }
 });
 function addActive(x) {
  /*a function to classify an item as "active":*/
  if (!x) return false;
  /*start by removing the "active" class on all items:*/
  removeActive(x);
  if (currentFocus >= x.length) currentFocus = 0;
  if (currentFocus < 0) currentFocus = (x.length - 1);
  /*add class "autocomplete-active":*/
  x[currentFocus].classList.add("autocomplete-active");
 }
 function removeActive(x) {
  /*a function to remove the "active" class from all autocomplete items:*/
  for (var i = 0; i < x.length; i++) {
   x[i].classList.remove("autocomplete-active");
  }
 }
 function closeAllLists(elmnt) {
  /*close all autocomplete lists in the document,
  except the one passed as an argument:*/
  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]);
   }
  }
 }
 /*execute a function when someone clicks in the document:*/
 document.addEventListener("click", function (e) {
   closeAllLists(e.target);
   });
}

/*数组 - 包含所有国家或地区名*/
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 China","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 China","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 China","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"];

/*传递参数*/
autocomplete(document.getElementById("myInput"), countries);

2.CSS部分

* { box-sizing: border-box; }
body {
 font: 16px Arial; 
}
.autocomplete {
 /*the container must be positioned relative:*/
 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;
 /*position the autocomplete items to be the same width as the container:*/
 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 {
 /*when hovering an item:*/
 background-color: #e9e9e9; 
}
.autocomplete-active {
 /*when navigating through the items using the arrow keys:*/
 background-color: DodgerBlue !important; 
 color: #ffffff; 
}

3.HTML部分

<!-- 关闭自带的自动补全功能 -->
<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>

4.效果图

JS实现联想、自动补齐国家或地区名称的功能

以上就是JS实现联想、自动补齐国家或地区名称的功能的详细内容,更多关于JS 联想、自动补齐功能的资料请关注三水点靠木其它相关文章!

Javascript 相关文章推荐
javascript radio 联动效果
Mar 04 Javascript
25个优雅的jQuery Tooltip插件推荐
May 25 Javascript
jquery Mobile入门—多页面切换示例学习
Jan 08 Javascript
showModalDialog在谷歌浏览器下会返回Null的解决方法
Nov 27 Javascript
使用jQuery和PHP实现类似360功能开关效果
Feb 12 Javascript
JavaScript学习笔记--常用的互动方法
Dec 07 Javascript
Element-UI Table组件上添加列拖拽效果实现方法
Apr 14 Javascript
详解基于node.js的脚手架工具开发经历
Jan 28 Javascript
three.js利用卷积法如何实现物体描边效果
Nov 27 Javascript
react+antd 递归实现树状目录操作
Nov 02 Javascript
关于Vue中的options选项
Mar 22 Vue.js
vue elementUI表格控制对应列
Apr 13 Vue.js
jQuery 动态粒子效果示例代码
Jul 07 #jQuery
Electron实现应用打包、自动升级过程解析
Jul 07 #Javascript
基于Electron实现桌面应用开发代码实例
Jul 07 #Javascript
基于javascript处理nginx请求过程详解
Jul 07 #Javascript
vue-i18n实现中英文切换的方法
Jul 06 #Javascript
vue 实现动态路由的方法
Jul 06 #Javascript
Nuxt配置Element-UI按需引入的操作方法
Jul 06 #Javascript
You might like
php中防止伪造跨站请求的小招式
2011/09/02 PHP
php通过exif_read_data函数获取图片的exif信息
2015/05/21 PHP
简单了解PHP编程中数组的指针的使用
2015/11/30 PHP
PHP实现多级分类生成树的方法示例
2017/02/07 PHP
Yii2中hasOne、hasMany及多对多关联查询的用法详解
2017/02/15 PHP
PHP进阶学习之命名空间基本用法分析
2019/06/18 PHP
TNC vs IO BO3 第一场2.13
2021/03/10 DOTA
Prototype 学习 工具函数学习($方法)
2009/07/12 Javascript
jQuery对象和DOM对象的相互转化实现代码
2010/03/02 Javascript
javascript代码加载优化方法
2011/01/30 Javascript
JS打印gridview实现原理及代码
2013/02/05 Javascript
jquery 无限级联菜单案例分享
2013/03/26 Javascript
Web Inspector:关于在 Sublime Text 中调试Js的介绍
2013/04/18 Javascript
加载远程图片时,经常因为缓存而得不到更新的解决方法(分享)
2013/06/26 Javascript
基于jquery的禁用右键、文本选择功能、复制按键的实现代码
2013/08/27 Javascript
javascript实现的一个随机点名功能
2014/08/26 Javascript
Javascript实现计算个人所得税
2015/05/10 Javascript
JS模式之单例模式基本用法
2015/06/30 Javascript
使用伪命名空间封装保护独自创建的对象方法
2016/08/04 Javascript
JavaScript实现时钟滴答声效果
2017/01/29 Javascript
基于Bootstrap漂亮简洁的CSS3价格表(附源码下载)
2017/02/28 Javascript
Vue中建立全局引用或者全局命令的方法
2017/08/21 Javascript
Node.JS使用Sequelize操作MySQL的示例代码
2017/10/09 Javascript
微信小程序仿朋友圈发布动态功能
2018/07/15 Javascript
Vue-router的使用和出现空白页,路由对象属性详解
2018/09/03 Javascript
jquery+ajax实现上传图片并显示上传进度功能【附php后台接收】
2019/06/06 jQuery
原生JavaScript实现五子棋游戏
2020/11/09 Javascript
如何使用 vue-cli 创建模板项目
2020/11/19 Vue.js
python实现冒泡排序算法的两种方法
2018/03/10 Python
Python实现购物车购物小程序
2018/04/18 Python
Python编程图形库之Pillow使用方法讲解
2018/12/28 Python
Python3.7基于hashlib和Crypto实现加签验签功能(实例代码)
2019/12/04 Python
HTML5未来发展趋势
2016/02/01 HTML / CSS
小学关爱留守儿童活动方案
2014/08/25 职场文书
总经理2015中秋节致辞
2015/07/29 职场文书
Spring Cloud OAuth2实现自定义token返回格式
2022/06/25 Java/Android