源代码来自于: http://down.51cto.com/data/921955  我做了一下修改.

要做一个自动完成的功能,又不想依赖一大堆的js脚本库,我要的是定制的,代码尽可能简洁,方便修改和维护.

网上找过jquery的autocomplate,样式太多,功能太多,我不需要.还有一些数据源分为数组和ajax返回值,数组写死的,我不要.

皇天不负有心人,让我在51上找到这个, 我修改了一下,贴出来跟大家分享一下.

 /**
 * JavaScript inputSuggest v0.1
 * Copyright (c) 2010 snandy
 * Blog: http://snandy.javaeye.com/
 * QQ群: 34580561
 * Date: 2010-09-25
 * Download by http://down.liehuo.net
 *
 * new InputSuggest({
 *       input         HTMLInputElement 必选
 *       data             Array ['sina.cn','sina.com','2008.sina.com','vip.sina.com.cn'] 必选
 *       containerCls    容器className
 *       itemCls        容器子项className
 *       activeCls        高亮子项className
 *       width         宽度设置 此项将覆盖containerCls的width
 *    opacity        透明度设置 此项将覆盖containerCls的opacity
 * });
 */

 function InputSuggest(opt) {
     this.win = null;
     this.doc = null;
     this.container = null;
     this.items = null;
     this.input = opt.input || null;
     this.containerCls = opt.containerCls || 'suggest-container';
     this.itemCls = opt.itemCls || 'suggest-item';
     this.activeCls = opt.activeCls || 'suggest-active';
     this.width = opt.width;
     this.opacity = opt.opacity;
     this.data = opt.data || [];
     this.active = null;
     this.visible = false;
     this.init();
 }
 InputSuggest.prototype = {
     init: function () {
         this.win = window;
         this.doc = window.document;
         this.container = this.$C('div');
         this.attr(this.container, 'class', this.containerCls);
         this.doc.body.appendChild(this.container);
         this.setPos();
         var _this = this, input = this.input;

         this.on(input, 'keyup', function (e) {
             if (input.value == '') {
                 _this.hide();
             } else {
                 _this.onKeyup(e);
             }

         });
         // blur会在click前发生,这里使用mousedown
         this.on(input, 'blur', function (e) {
             _this.hide();
         });
         this.onMouseover();
         this.onMousedown();

     },
     $C: function (tag) {
         return this.doc.createElement(tag);
     },
     getPos: function (el) {
         var pos = [0, 0], a = el;
         if (el.getBoundingClientRect) {
             var box = el.getBoundingClientRect();
             pos = [box.left, box.top];
         } else {
             while (a && a.offsetParent) {
                 pos[0] += a.offsetLeft;
                 pos[1] += a.offsetTop;
                 a = a.offsetParent
             }
         }
         return pos;
     },
     setPos: function () {
         var input = this.input,
             pos = this.getPos(input),
             brow = this.brow,
             width = this.width,
             opacity = this.opacity,
             container = this.container;
         container.style.cssText =
             'position:absolute;overflow:hidden;left:'
             + pos[0] + 'px;top:'
             + (pos[1] + input.offsetHeight) + 'px;width:'
         // IE6/7/8/9/Chrome/Safari input[type=text] border默认为2,Firefox为1,因此取offsetWidth-2保证与FF一致
             + (brow.firefox ? input.clientWidth : input.offsetWidth - 2) + 'px;';
         if (width) {
             container.style.width = width + 'px';
         }
         if (opacity) {
             if (this.brow.ie) {
                 container.style.filter = 'Alpha(Opacity=' + opacity * 100 + ');';
             } else {
                 container.style.opacity = (opacity == 1 ? '' : '' + opacity);
             }
         }
     },
     show: function () {
         this.container.style.visibility = 'visible';
         this.visible = true;
     },
     hide: function () {
         this.container.style.visibility = 'hidden';
         this.visible = false;
     },
     attr: function (el, name, val) {
         if (val === undefined) {
             return el.getAttribute(name);
         } else {
             el.setAttribute(name, val);
             name == 'class' && (el.className = val);
         }
     },
     on: function (el, type, fn) {
         el.addEventListener ? el.addEventListener(type, fn, false) : el.attachEvent('on' + type, fn);
     },
     un: function (el, type, fn) {
         el.removeEventListener ? el.removeEventListener(type, fn, false) : el.detachEvent('on' + type, fn);
     },
     brow: function (ua) {
         return {
             ie: /msie/.test(ua) && !/opera/.test(ua),
             opera: /opera/.test(ua),
             firefox: /firefox/.test(ua)
         };
     } (navigator.userAgent.toLowerCase()),
     onKeyup: function (e) {
         var container = this.container, input = this.input, iCls = this.itemCls, aCls = this.activeCls;
         if (this.visible) {
             switch (e.keyCode) {
                 case 13: // Enter
                     if (this.active) {
                         input.value = this.active.firstChild.data;
                         this.hide();
                     }
                     return;
                 case 38: // 方向键上
                     if (this.active == null) {
                         this.active = container.lastChild;
                         this.attr(this.active, 'class', aCls);
                         input.value = this.active.firstChild.data;
                     } else {
                         if (this.active.previousSibling != null) {
                             this.attr(this.active, 'class', iCls);
                             this.active = this.active.previousSibling;
                             this.attr(this.active, 'class', aCls);
                             input.value = this.active.firstChild.data;
                         } else {
                             this.attr(this.active, 'class', iCls);
                             this.active = null;
                             input.focus();
                             input.value = input.getAttribute("curr_val");
                         }
                     }
                     return;
                 case 40: // 方向键下
                     if (this.active == null) {
                         this.active = container.firstChild;
                         this.attr(this.active, 'class', aCls);
                         input.value = this.active.firstChild.data;
                     } else {
                         if (this.active.nextSibling != null) {
                             this.attr(this.active, 'class', iCls);
                             this.active = this.active.nextSibling;
                             this.attr(this.active, 'class', aCls);
                             input.value = this.active.firstChild.data;
                         } else {
                             this.attr(this.active, 'class', iCls);
                             this.active = null;
                             input.focus();
                             input.value = input.getAttribute("curr_val");
                         }
                     }
                     return;

             }

         }
         if (e.keyCode == 27) { // ESC键
             this.hide();
             input.value = this.attr(input, 'curr_val');
             return;
         }
         if (input.value.indexOf('@') != -1) { return; }
         this.items = [];

         if (this.attr(input, 'curr_val') != input.value) {
             this.container.innerHTML = '';
             for (var i = 0, len = this.data.length; i < len; i++) {

                 if (this.data[i].toLowerCase().indexOf(input.value.toLowerCase()) >= 0) {
                     var item = this.$C('div'); //create div
                     this.attr(item, 'class', this.itemCls);
                     //item.innerHTML = input.value + '@' + this.data[i];
                     item.innerHTML =  this.data[i]; // 修改源代码处
                     this.items[i] = item;
                     this.container.appendChild(item);
                 }
             }
             this.attr(input, 'curr_val', input.value);
         }

         this.show();
     },
     onMouseover: function () {
         var _this = this, icls = this.itemCls, acls = this.activeCls;
         this.on(this.container, 'mouseover', function (e) {
             var target = e.target || e.srcElement;
             if (target.className == icls) {
                 if (_this.active) {
                     _this.active.className = icls;
                 }
                 target.className = acls;
                 _this.active = target;
             }
         });
     },
     onMousedown: function () {
         var _this = this;
         this.on(this.container, 'mousedown', function (e) {
             var target = e.target || e.srcElement;
             _this.input.value = target.innerHTML;
             _this.hide();
         });
     }
 }    

画面上是这样调用的

 <!DOCTYPE HTML>
 <html>
 <head>
     <meta charset="utf-8">
     <title></title>
     <style type="text/css">
         body
         {
             margin: 0;
             padding: 0;
         }
         input
         {
             width: 200px;
         }
         .suggest-container
         {
             border: 1px solid #C1C1C1;
             visibility: hidden;
             background-color: White;
             z-index: 9999;
         }
         .suggest-item
         {
             padding: 3px 2px;
         }
         .suggest-active
         {
             background: #33CCFF;
             color: white;
             padding: 3px 2px;
         }
     </style>
     <script src="../Scripts/jquery-1.4.1.js" type="text/javascript"></script>
     <script src="../Scripts/autoComplateTool.js" type="text/javascript"></script>
     <script type="text/javascript">

         $(document).ready(function () {
             $("#guitai").focus(function () {
                 var aToStr = $("#txtea_L").val();
                 aToStr = $.trim(aToStr);
                 var data = eval("(" + aToStr + ")");
                 var arrSource = [];

                 for (var i = 0; i < data.length; i++) {
                     arrSource.push(data[i].E);
                 }

                 var sinaSuggest = new InputSuggest({
                     width: 300,
                     opacity: 0.8,
                     input: document.getElementById('guitai'),
                     data: arrSource
                     //['sina.cn', 'sina.com', 'vip.sina.com.cn', '2008.sina.com', '263.sina.com']
                 });
             });
         });
     </script>
 </head>
 <body>
     <div style="width: 400px; margin: 30px auto; text-align: center;">
         <label>
             柜台</label>
         <input type="text" id="guitai" />
         <br />
         <br />
     </div>
     <div>
         <textarea id="txtea_L" style="width: 1550px; height: 100px;">
            [ { 'A': 'DEP00000', 'B': '直营专柜', 'C': 'DEP0000XXXX','D': '直属', 'E': 'DEPFFFF',
             'F': '上海地区','CounterKey': '000101', 'CounterName': '上海巴春五角场' },
             {'A':'R1','B':'华东大区','C':'1010','D':'福建分公司','E':'DEPGFF','F':'赵子龙',
              'G':'1010500007841','H':'XXXX化妆品店'} ]
            </textarea>
     </div>
 </body>
 </html>

完结撒花! Nice.

js自动完成的更多相关文章

  1. MyEclipse 中 添加 js自动完成模版

    MyEclipse 中 添加 js自动完成模版: window>preference>MyEclipse>Files and Editors>JavaScript>Edi ...

  2. 【XSS】对抗蠕虫 —— 如何让按钮不被 JS 自动点击

    前言 XSS 自动点按钮有什么危害? 在社交网络里,很多操作都是通过点击按钮发起的,例如发表留言.假如留言系统有 XSS,用户中招后除了基本攻击外,还能进行传播 -- XSS 自动填入留言内容,并模拟 ...

  3. js 自动类型转换

    js自动类型转换 1.==符号在判断左右两边数据是否相等时,如果数据类型一致,直接比较值即可 2.==符号左右数据类型不一致时,如果两方数据为布尔型.数值型.字符串型时,不为数字的那一方自动调用Num ...

  4. pageresponse.min.js自动缩放页面改写

    /* * 名称 :移动端响应式框架 * 作者 :白树 http://peunzhang.cnblogs.com * 版本 :v2.1 * 日期 :2015.10.13 * 兼容 :ios 5+.and ...

  5. js自动访问数据库

    js自动访问数据库 maven依赖 <dependencies> <dependency> <groupId>junit</groupId> <a ...

  6. node-webkit-updater——NW.js自动更新

    NW.js自动更新三种方案: 1)node-webkit-updater(推荐) 2)nwjs-autoupdater 3)nw-autoupdater NW.js自动更新三种方案:[http://d ...

  7. js自动生成条形码插件-JsBarcode

    JsBarcode.html <!DOCTYPE html> <html lang="en"> <head> <meta charset= ...

  8. Cleave.js – 自动格式化表单输入框的文本内容

    Cleave.js 有一个简单的目的:帮助你自动格式输入的文本内容. 这个想法是提供一个简单的方法来格式化您的输入数据以增加输入字段的可读性.通过使用这个库,您不需要编写任何正则表达式来控制输入文本的 ...

  9. js 自动插入分号

    先来看一个例子: function get(){ return { a:1 } } var r=get(); console.log(r); 似乎r的值应该是{a:1},然而运行结果却是undefin ...

随机推荐

  1. C算法编程题系列

    我的编程开始(C) C算法编程题(一)扑克牌发牌 C算法编程题(二)正螺旋 C算法编程题(三)画表格 C算法编程题(四)上三角 C算法编程题(五)“E”的变换 C算法编程题(六)串的处理 C算法编程题 ...

  2. php对文本文件进行分页功能简单实现

    php对文本文件进行分页功能简单实现 <!DOCTYPE> <html> <head> <meta http-equiv="Content-type ...

  3. jQuery中的Sizzle引擎分析

    我分析的jQuery版本是1.8.3.Sizzle代码从3669行开始到5358行,将近2000行的代码,这个引擎的版本还是比较旧,最新的版本已经到v2.2.2了,代码已经超过2000行了.并且还有个 ...

  4. 记录一则ORA-00054,ORA-00031解决过程

    生产环境:AIX 5.3 + Oracle 10.2.0.5 任务要求:普通表改造分区表,历史数据不要   这个需求很简单: pl/sql导出建表语句,依次修改成分区的建表语句,注意将索引修改成本地索 ...

  5. 重温JSP学习笔记--三大指令九大内置对象

    最近在温习javaweb的相关基础知识,鉴于我弄丢了记满了整整一本的笔记,决定以后把笔记和一些学习上的心得以及碰到的一些问题统统都放在网上,今天看了一下jsp的相关基础,以下是笔记: JSP三大指令: ...

  6. Cesium原理篇:6 Render模块(6: Instance实例化)

    最近研究Cesium的实例化,尽管该技术需要在WebGL2.0,也就是OpenGL ES3.0才支持.调试源码的时候眼前一亮,发现VAO和glDrawBuffers都不是WebGL1.0的标准函数,都 ...

  7. 移动端上传照片 预览+Draw on Canvas's Demo(解决 iOS 等设备照片旋转 90 度的 bug)

    背景: 本人的一个移动端H5项目,需求如下: 需求一:手机相册选取或拍摄照片后在页面上预览 需求二:然后绘制在canvas画布上 这里,我们先看一个demo(http://jsfiddle.net/q ...

  8. WebGIS中解决使用Lucene进行兴趣点搜索排序的两种思路

    文章版权由作者李晓晖和博客园共有,若转载请于明显处标明出处:http://www.cnblogs.com/naaoveGIS/. 1.背景 目前跟信息采集相关的一个项目提出了这样的一个需求:中国银行等 ...

  9. APP接口自动化测试JAVA+TestNG(三)之HTTP接口测试实例

    前言     前两篇普及相关基础知识后,本篇主要对举例对国家气象局接口自动化测试进行讲解(Get请求及结果断言),以达到自动化测试入门目的,除了前两篇的一些了解外,需要有一定的JAVA知识(HTTP相 ...

  10. 在webstorm设置File watcher for Jade

    用Jade模板引擎写html确实方便,元素不用闭合,很多种简写的方法. 为了要知道自己写的对不对,就要用到jade -w命令监控jade文件,只要变化就编译. 现在用webstorm写代码的超多,可以 ...