>  기사  >  웹 프론트엔드  >  JS 입력 상자 사서함 자동 프롬프트 함수 코드 구현_javascript 기술

JS 입력 상자 사서함 자동 프롬프트 함수 코드 구현_javascript 기술

WBOY
WBOY원래의
2016-05-16 17:10:041191검색

마찬가지로 이 플러그인에는 html 태그가 필요하지 않으며 해당 클래스 이름이 있는 입력 상자만 필요하고 상위에는 클래스 이름이 있으며 다른 것은 필요하지 않습니다. 내부 HTML 코드가 자동으로 생성됩니다.

HTML 코드는 다음과 같습니다.

코드 복사 코드는 다음과 같습니다.



사실 위의 div 태그는 필요하지 않습니다. 입력 입력 상자와 상위 요소에 위와 같이 클래스를 추가하기만 하면 됩니다. (사용자 정의할 수도 있으며, JS 초기화 중에 클래스를 전달하면 됩니다. 기본적으로 부모 클래스는 parentCls라고 하고, 현재 입력 상자 클래스는 inputElem이라고 하며, 숨겨진 필드의 클래스는 HiddenCls라고 합니다. 초기화하는 동안 빈 객체를 직접 초기화하고 전달하세요!) 페이지에 여러 개의 입력 상자가 있을 수 있으므로 어떤 입력 상자인지 구별하려면 상위 클래스가 필요합니다. 물론 개발 백엔드에 값을 저장하려면 숨겨진 필드가 필요합니다.

구성 항목에 메일함 배열 매개변수인 mailArr이 있습니다: ["@qq.com", "@qq2.com", "@gmail.com", "@126.com", "@163.com" ,"@hotmail.com","@yahoo.com","@yahoo.com.cn","@live.com","@sohu.com","@sina.com"]. 내가 무엇을 입력하든 드롭다운 상자가 초기화되면 기본 사서함이 너무 많다는 것을 알려주는 것입니다. 드롭다운 상자의 항목입니다. 물론 요구사항 변경으로 인해 이메일 매개변수를 초기화할 때 필요에 따라 구성할 수 있습니다.

코딩 스타일은 이전과 동일합니다.

구현된 기능은 다음과 같습니다.

1. 키보드 상하 이동, 마우스 클릭 및 입력 동작을 지원합니다.

2. 문서를 클릭하면 현재 입력 상자를 제외하고 드롭다운 상자가 숨겨집니다. 계속 입력하시면 자동 매칭 및 기타 동작이 구현됩니다.

자세히 설명하지 않겠습니다. 온라인 등록 시 자동 이메일 알림 기능과 같습니다. 버그가 있으면 메시지를 남겨주세요. 코드를 직접 붙여넣으세요.

CSS 코드는 다음과 같습니다.

코드 복사 코드는 다음과 같습니다.


JS 코드는 다음과 같습니다.

코드 복사 코드는 다음과 같습니다.

/**
 * 邮箱自动提示插件
 * @constructor EmailAutoComplete
 * @ options {object} 可配置项
 */

 function EmailAutoComplete(options) {

    this.config = {
        targetCls      :  '.inputElem',       // 目标input元素
        parentCls      :  '.parentCls',       // 当前input元素的父级类
        hiddenCls      :  '.hiddenCls',       // 当前input隐藏域
        searchForm     :  '.jqtransformdone', //form表单
        hoverBg        :  'hoverBg',          // 鼠标移上去的背景
        inputValColor  :  'red',              // 输入框输入提示颜色
        mailArr        : ["@qq.com","@qq2.com","@gmail.com","@126.com","@163.com","@hotmail.com","@yahoo.com","@yahoo.com.cn","@live.com","@sohu.com","@sina.com"], //邮箱数组
        isSelectHide   : true,                // 点击下拉框 是否隐藏 默认为true
        callback       : null                 // 点击某一项回调函数
    };
    this.cache = {
        onlyFlag            : true,     // 只渲染一次
        currentIndex        : -1,
        oldIndex            : -1
    };

    this.init(options);
 }

EmailAutoComplete.prototype = {

    constructor: EmailAutoComplete,

    init: function(options){
        this.config = $.extend(this.config,options || {});

        var self = this,
            _config = self.config,
            _cache = self.cache;

        $(_config.targetCls).each(function(index,item){

            $(item).keyup(function(e){
                var target = e.target,
                    targetVal = $.trim($(this).val()),
                    keycode = e.keyCode,
                    elemHeight = $(this).outerHeight(),
                    elemWidth = $(this).outerWidth(),
                    parentNode = $(this).closest(_config.parentCls);

                $(parentNode).css({'position':'relative'});
                // 如果输入框值为空的话 那么下拉框隐藏
                if(targetVal == '') {
                    $(item).attr({'data-html':''});
                    // 给隐藏域赋值
                    $(_config.hiddenCls,parentNode).val('');

                    _cache.currentIndex = -1;
                    _cache.oldIndex = -1;
                    $(".auto-tip",parentNode) && !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden');
                    self._removeBg(parentNode);
                }else {

                    $(item).attr({'data-html':targetVal});

                    // 给隐藏域赋值
                    $(_config.hiddenCls,parentNode).val(targetVal);

                    $(".auto-tip",parentNode) && $(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).removeClass('hidden');
                    // 渲染下拉框内容
                    self._renderHTML({keycode:keycode,e:e,target:target,targetVal:targetVal,height:elemHeight,width:elemWidth,parentNode:parentNode});
                }

               
            });
        });

       // 阻止form表单默认enter键提交
       $(_config.searchForm).each(function(index,item) {
            $(item).keydown(function(e){
                 var keyCode = e.keyCode;
                 if(keyCode == 13) {
                     return false;
                 }
            });
       });

       // 点击文档document时候 下拉框隐藏掉
       $(document).click(function(e){
          e.stopPropagation();
          var target = e.target,
              tagCls = _config.targetCls.replace(/^\./,'');

          if(!$(target).hasClass(tagCls)) {
             $('.auto-tip') && $('.auto-tip').each(function(index,item){
                 !$(item).hasClass('hidden') && $(item).addClass('hidden');
             });
          }
       });
    },
    /*
     * 渲染下拉框提示内容
     * @param cfg{object}
     */
    _renderHTML: function(cfg) {
        var self = this,
            _config = self.config,
            _cache = self.cache,
            curVal;
        var curIndex = self._keyCode(cfg.keycode);

        $('.auto-tip',cfg.parentNode).hasClass('hidden') && $('.auto-tip',cfg.parentNode).removeClass('hidden');
        if(curIndex > -1){
            // 键盘上下操作
            self._keyUpAndDown(cfg.targetVal,cfg.e,cfg.parentNode);
        }else {
            if(/@/.test(cfg.targetVal)) {
                curVal = cfg.targetVal.replace(/@.*/,'');
            }else {
                curVal = cfg.targetVal;
            }
            if(_cache.onlyFlag) {
                $(cfg.parentNode).append('');
                var wrap = '

    ';

                    for(var i = 0; i < _config.mailArr.length; i++) {

    wrap += '

  • '+''+_config.mailArr[i]+'
  • ';
                    }
                    wrap += '
';
                _cache.onlyFlag = false;
                $(cfg.parentNode).append(wrap);
                $('.auto-tip',cfg.parentNode).css({'position':'absolute','top':cfg.height,'width':cfg.width - 2 + 'px','left':0,
                    'border':'1px solid #ccc','z-index':10000});
            }

            // 给所有li添加属性 data-html
            $('.auto-tip li',cfg.parentNode).each(function(index,item){
                $('.output-num',item).html(curVal);
                !$('.output-num',item).hasClass(_config.inputValColor) &&
                $('.output-num',item).addClass(_config.inputValColor);
                var emVal = $.trim($('.em',item).attr('data-html'));
                $(item).attr({'data-html':curVal + '' +emVal});
            });

            // 精确匹配内容
            self._accurateMate({target:cfg.target,parentNode:cfg.parentNode});

            // 鼠标移到某一项li上面时候
            self._itemHover(cfg.parentNode);

            // 点击对应的项时
            self._executeClick(cfg.parentNode);
        }

    },
    /**
     * 精确匹配某项内容
     */
    _accurateMate: function(cfg) {
        var self = this,
            _config = self.config,
            _cache = self.cache;

        var curVal = $.trim($(cfg.target,cfg.parentNode).attr('data-html')),
            newArrs = [];
        if(/@/.test(curVal)) {

            // 获得@ 前面 后面的值
            var prefix = curVal.replace(/@.*/, ""),
                suffix = curVal.replace(/.*@/, "");

            $.map(_config.mailArr,function(n){
                var reg = new RegExp(suffix);
                if(reg.test(n)) {
                    newArrs.push(n);
                }
            });
            if(newArrs.length > 0) {
                $('.auto-tip',cfg.parentNode).html('');
                $(".auto-tip",cfg.parentNode) && $(".auto-tip",cfg.parentNode).hasClass('hidden') &&
                $(".auto-tip",cfg.parentNode).removeClass('hidden');

                var html = '';
                for(var j = 0, jlen = newArrs.length; j < jlen; j++) {
html += '

  • '+''+newArrs[j]+'
  • ';
                    }
                    $('.auto-tip',cfg.parentNode).html(html);

                    // 给所有li添加属性 data-html
                    $('.auto-tip li',cfg.parentNode).each(function(index,item){
                        $('.output-num',item).html(prefix);
                        !$('.output-num',item).hasClass(_config.inputValColor) &&
                        $('.output-num',item).addClass(_config.inputValColor);

                        var emVal = $.trim($('.em',item).attr('data-html'));

                        $(item).attr('data-html','');
                        $(item).attr({'data-html':prefix + '' +emVal});
                    });

                    // 精确匹配到某项时候 让当前的索引等于初始值
                    _cache.currentIndex = -1;
                    _cache.oldIndex = -1;

                    $('.auto-tip .output-num',cfg.parentNode).html(prefix);

                    // 鼠标移到某一项li上面时候
                    self._itemHover(cfg.parentNode);

                    // 点击对应的项时
                    self._executeClick(cfg.parentNode);
                }else {
                    $(".auto-tip",cfg.parentNode) && !$(".auto-tip",cfg.parentNode).hasClass('hidden') &&
                    $(".auto-tip",cfg.parentNode).addClass('hidden');
                    $('.auto-tip',cfg.parentNode).html('');
                }
            }
        },
        /*
         * 鼠标移到某一项li上时
         */
        _itemHover: function(parentNode) {
            var self = this,
                _config = self.config,
                _cache = self.cache;
            $('.auto-tip li',parentNode).hover(function(index,item) {
                !$(this).hasClass(_config.hoverBg) && $(this).addClass(_config.hoverBg);
            },function() {
                $(this).hasClass(_config.hoverBg) && $(this).removeClass(_config.hoverBg);
            });
        },
        /*
         * 当输入框值为空时候 li项都删掉class hoverBg
         */
        _removeBg: function(parentNode){
            var self = this,
                _config = self.config;

            $(".auto-tip li",parentNode).each(function(index,item){
                $(item).hasClass(_config.hoverBg) && $(item).removeClass(_config.hoverBg);
            });   
        },
        /**
         * 键盘上下键操作
         */
         _keyUpAndDown: function(targetVal,e,parentNode) {
            var self = this,
                _cache = self.cache,
                _config = self.config;

            // 如果请求成功后 返回了数据(根据元素的长度来判断) 执行以下操作
            if($('.auto-tip' + ' li',parentNode) && $('.auto-tip' + ' li').length > 0) {

                var plen = $('.auto-tip' + ' li',parentNode).length,
                    keyCode = e.keyCode;
                    _cache.oldIndex = _cache.currentIndex;
               

                // 上移操作
                if(keyCode == 38) {
                    if(_cache.currentIndex == -1) {
                        _cache.currentIndex = plen - 1;
                    }else {
                        _cache.currentIndex = _cache.currentIndex - 1;
                        if(_cache.currentIndex < 0) {
    _cache.currentIndex = plen - 1;
    }
    }
    if(_cache.currentIndex !== -1) {

    !$('.auto-tip .p-index'+_cache.currentIndex,parentNode).hasClass(_config.hoverBg) &&
    $('.auto-tip .p-index'+_cache.currentIndex,parentNode).addClass(_config.hoverBg).siblings().removeClass(_config.hoverBg);

    var curAttr = $('.auto-tip' + ' .p-index'+_cache.currentIndex,parentNode).attr('data-html');
    $(_config.targetCls,parentNode).val(curAttr);

    // 给隐藏域赋值
    $(_config.hiddenCls,parentNode).val(curAttr);
    }

    }else if(keyCode == 40) { //下移操作
    if(_cache.currentIndex == plen - 1) {
    _cache.currentIndex = 0;
    }else {
    _cache.currentIndex++;
    if(_cache.currentIndex > plen - 1) {
                            _cache.currentIndex = 0;
                        }
                    }

                    if(_cache.currentIndex !== -1) {

                        !$('.auto-tip .p-index'+_cache.currentIndex,parentNode).hasClass(_config.hoverBg) &&
                        $('.auto-tip .p-index'+_cache.currentIndex,parentNode).addClass(_config.hoverBg).siblings().removeClass(_config.hoverBg);

                        var curAttr = $('.auto-tip' + ' .p-index'+_cache.currentIndex,parentNode).attr('data-html');
                        $(_config.targetCls,parentNode).val(curAttr);
                        // 给隐藏域赋值
                        $(_config.hiddenCls,parentNode).val(curAttr);
                    }

                }else if(keyCode == 13) { //回车操作
                    var curVal = $('.auto-tip' + ' .p-index'+_cache.oldIndex,parentNode).attr('data-html');
                    $(_config.targetCls,parentNode).val(curVal);

                    // 给隐藏域赋值
                    $(_config.hiddenCls,parentNode).val(curVal);

                    if(_config.isSelectHide) {
                         !$(".auto-tip",parentNode).hasClass('hidden') && $(".auto-tip",parentNode).addClass('hidden');
                     }
                     _config.callback && $.isFunction(_config.callback) && _config.callback();

                    _cache.currentIndex = -1;
                    _cache.oldIndex = -1;

                }
            }
         },
         _keyCode: function(code) {
             var arrs = ['17','18','38','40','37','39','33','34','35','46','36','13','45','44','145','19','20','9'];
             for(var i = 0, ilen = arrs.length; i < ilen; i++) {
                 if(code == arrs[i]) {
                     return i;
                 }
             }
             return -1;
         },
        /**
          * 当数据相同的时 点击对应的项时 返回数据
          */
         _executeClick: function(parentNode) {

             var _self = this,
                 _config = _self.config;

             $('.auto-tip' + ' li',parentNode).unbind('click');
             $('.auto-tip' + ' li',parentNode).bind('click',function(e){
                  var dataAttr = $(this).attr('data-html');

                  $(_config.targetCls,parentNode).val(dataAttr);
                  if(_config.isSelectHide) {
                    !$(".auto-tip",parentNode).hasClass('hidden') && 달러 ttr);
                 _config.callback && $.isFunction(_config.callback) && _config.callback();

             });
         }
    };

    // 初始化
    $(function() {

        new EmailAutoComplete({});

    });


    성명:
    본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.