>  기사  >  웹 프론트엔드  >  jquery는 email_javascript 기술을 입력할 때 자동 완성 드롭다운 프롬프트 기능을 구현합니다.

jquery는 email_javascript 기술을 입력할 때 자동 완성 드롭다운 프롬프트 기능을 구현합니다.

WBOY
WBOY원래의
2016-05-16 15:37:301427검색

작년에 프로젝트 작업을 할 때 이메일 입력 시 자동 프롬프트 기능을 사용하다가 인터넷에서 검색하다가 이렇게 잘 쓰여진 글을 발견하고 생각나서 참고하기 쉽게 다시 인쇄하게 되었습니다. .

이메일은 무료이기 때문에 널리 사용되기 때문에 많은 웹사이트에서 등록 시 이메일을 계정 이름으로 직접 사용합니다

사용자 경험을 개선하기 위해 많은 웹사이트에서는 이메일 입력에 대한 자동 프롬프트 기능을 구현할 예정입니다.

효과는 그림과 같습니다.

핵심 코드(jquery 지원 필요):

(function($){
  $.fn.mailAutoComplete = function(options){
    var defaults = {
      boxClass: "mailListBox", //外部box样式
      listClass: "mailListDefault", //默认的列表样式
      focusClass: "mailListFocus", //列表选样式中
      markCalss: "mailListHlignt", //高亮样式
      zIndex: 1,
      autoClass: true, //是否使用插件自带class样式
      mailArr: ["qq.com","gmail.com","126.com","163.com","hotmail.com","yahoo.com","yahoo.com.cn","live.com","sohu.com","sina.com"], //邮件数组
      textHint: false, //文字提示的自动显示与隐藏
      hintText: "",
      focusColor: "#333"
      //blurColor: "#999"
    };
    var settings = $.extend({}, defaults, options || {});
    
    //页面装载CSS样式
    if(settings.autoClass && $("#mailListAppendCss").size() === 0){
      $('<style id="mailListAppendCss" type="text/css">.mailListBox{border:1px solid #369; background:#fff; font:12px/20px Arial;}.mailListDefault{padding:0 5px;cursor:pointer;white-space:nowrap;}.mailListFocus{padding:0 5px;cursor:pointer;white-space:nowrap;background:#369;color:white;}.mailListHlignt{color:red;}.mailListFocus .mailListHlignt{color:#fff;}</style>').appendTo($("head"));  
    }
    var cb = settings.boxClass, cl = settings.listClass, cf = settings.focusClass, cm = settings.markCalss; //插件的class变量
    var z = settings.zIndex, newArr = mailArr = settings.mailArr, hint = settings.textHint, text = settings.hintText, fc = settings.focusColor, bc = settings.blurColor;
    //创建邮件内部列表内容
    $.createHtml = function(str, arr, cur){
      var mailHtml = "";
      if($.isArray(arr)){
        $.each(arr, function(i, n){
          if(i === cur){
            mailHtml += '<div class="mailHover '+cf+'" id="mailList_'+i+'"><span class="'+cm+'">'+str+'</span>@'+arr[i]+'</div>';  
          }else{
            mailHtml += '<div class="mailHover '+cl+'" id="mailList_'+i+'"><span class="'+cm+'">'+str+'</span>@'+arr[i]+'</div>';  
          }
        });
      }
      return mailHtml;
    };
    //一些全局变量
    var index = -1, s;
    $(this).each(function(){
      var that = $(this), i = $(".justForJs").size();  
      if(i > 0){ //只绑定一个文本框
         return;  
      }
      var w = that.outerWidth(), h = that.outerHeight(); //获取当前对象(即文本框)的宽高
      //样式的初始化
      that.wrap('<span style="display:inline-block;position:relative;"></span>')
        .before('<div id="mailListBox_'+i+'" class="justForJs '+cb+'" style="min-width:'+w+'px;_width:'+w+'px;position:absolute;left:-6000px;top:'+h+'px;z-index:'+z+';"></div>');
      var x = $("#mailListBox_" + i), liveValue; //列表框对象
      that.focus(function(){
        //父标签的层级
        $(this).css("color", fc).parent().css("z-index", z);  
        //提示文字的显示与隐藏
        if(hint && text){
          var focus_v = $.trim($(this).val());
          if(focus_v === text){
            $(this).val("");
          }
        }
        //键盘事件
        $(this).keyup(function(e){
          s = v = $.trim($(this).val());  
          if(/@/.test(v)){
            s = v.replace(/@.*/, "");
          }
          if(v.length > 0){
            //如果按键是上下键
            if(e.keyCode === 38){
              //向上
              if(index <= 0){
                index = newArr.length;  
              }
              index--;
            }else if(e.keyCode === 40){
              //向下
              if(index >= newArr.length - 1){
                index = -1;
              }
              index++;
            }else if(e.keyCode === 13){
              //回车
              if(index > -1 && index < newArr.length){
                //如果当前有激活列表
                $(this).val($("#mailList_"+index).text());  
              }
            }else{
              if(/@/.test(v)){
                index = -1;
                //获得@后面的值
                //s = v.replace(/@.*/, "");
                //创建新匹配数组
                var site = v.replace(/.*@/, "");
                newArr = $.map(mailArr, function(n){
                  var reg = new RegExp(site);  
                  if(reg.test(n)){
                    return n;  
                  }
                });
              }else{
                newArr = mailArr;
              }
            }
            x.html($.createHtml(s, newArr, index)).css("left", 0);
            if(e.keyCode === 13){
              //回车
              if(index > -1 && index < newArr.length){
                //如果当前有激活列表
                x.css("left", "-6000px");  
              }
            }
          }else{
            x.css("left", "-6000px");  
          }
        }).blur(function(){
          if(hint && text){
            var blur_v = $.trim($(this).val());
            if(blur_v === ""){
              $(this).val(text);
            }
          }
          $(this).css("color", bc).unbind("keyup").parent().css("z-index",0);
          x.css("left", "-6000px");  
          
        });  
        //鼠标经过列表项事件
        //鼠标经过
        $(".mailHover").live("mouseover", function(){
          index = Number($(this).attr("id").split("_")[1]);  
          liveValue = $("#mailList_"+index).text();
          x.children("." + cf).removeClass(cf).addClass(cl);
          $(this).addClass(cf).removeClass(cl);
        });
      });

      x.bind("mousedown", function(){
        that.val(liveValue);    
      });
    });
  };
  
})(jQuery);

html 예:

<div class="reg_lin1">
<div class="lin1_1">常用邮箱:</div>
<div class="lin1_2"><input type="text" class = "reg_text" id = "email" name = "email"/></div>
<div class="lin1_3"></div>
</div>

jquery 코드 호출:

$("#email").mailAutoComplete({
boxClass: "out_box", //外部box样式
listClass: "list_box", //默认的列表样式
focusClass: "focus_box", //列表选样式中
markCalss: "mark_box", //高亮样式
autoClass: false,
textHint: true //提示文字自动隐藏
});

css, 원하는 색상으로 수정 가능

 <style type="text/css">
    .out_box{border:1px solid #ccc; background:#fff; font:12px/20px Tahoma;}
    .list_box{border-bottom:1px solid #eee; padding:0 5px; cursor:pointer;}
    .focus_box{background:#f0f3f9;}
    .mark_box{color:#c00;}
  </style>

효과 2:

1. 이 플러그인은 너비에 적응합니다. 즉, 내부 텍스트가 너무 길면 외부 div의 너비가 자동으로 확장됩니다. CSS를 사용자 정의할 때 너비 값을 설정하면 IE6 이외의 브라우저에서 너비 조정이 실패합니다.
2. 스타일의 가장 바깥쪽 상자에 대한 위치 속성이나 너비 및 높이를 설정할 필요가 없습니다. jQuery 플러그인에서 이러한 속성을 설정하는 것은 효과 표시에 도움이 되지 않습니다. 🎜> 3. 이 플러그인은 한 줄짜리 텍스트 상자에만 사용할 수 있습니다. 다른 라벨 유형의 요소에는 제한이 없으므로 바인딩 개체가 올바르지 않으면 예상치 못한 상황이 발생할 수 있습니다.
4. 이용 중 다양한 문의 및 버그 문의 환영합니다.
-------------------------------------
참고: 사용 방법
CSS 코드:

.out_box{border:1px solid #ccc; background:#fff; font:12px/20px Tahoma;}
.list_box{border-bottom:1px solid #eee; padding:0 5px; cursor:pointer;}
.focus_box{background:#f0f3f9;}
.mark_box{color:#c00;}
JS 코드:


$("#customTest").mailAutoComplete({
  boxClass: "out_box", //外部box样式
  listClass: "list_box", //默认的列表样式
  focusClass: "focus_box", //列表选样式中
  markCalss: "mark_box", //高亮样式
  autoClass: false,
  textHint: true, //提示文字自动隐藏
  hintText: "请输入邮箱地址"
});
(function($){
  $.fn.mailAutoComplete = function(options){
    var defaults = {
      boxClass: "mailListBox", //外部box样式
      listClass: "mailListDefault", //默认的列表样式
      focusClass: "mailListFocus", //列表选样式中
      markCalss: "mailListHlignt", //高亮样式
      zIndex: 1,
      autoClass: true, //是否使用插件自带class样式
      mailArr: ["qq.com","gmail.com","126.com","163.com","hotmail.com","yahoo.com","yahoo.com.cn","live.com","sohu.com","sina.com"], //邮件数组
      textHint: false, //文字提示的自动显示与隐藏
      hintText: "",
      focusColor: "#333",
      blurColor: "#999"
    };
    var settings = $.extend({}, defaults, options || {});
     
    //页面装载CSS样式
    if(settings.autoClass && $("#mailListAppendCss").size() === 0){
      $('<style id="mailListAppendCss" type="text/css">.mailListBox{border:1px solid #369; background:#fff; font:12px/20px Arial;}.mailListDefault{padding:0 5px;cursor:pointer;white-space:nowrap;}.mailListFocus{padding:0 5px;cursor:pointer;white-space:nowrap;background:#369;color:white;}.mailListHlignt{color:red;}.mailListFocus .mailListHlignt{color:#fff;}</style>').appendTo($("head")); 
    }
    var cb = settings.boxClass, cl = settings.listClass, cf = settings.focusClass, cm = settings.markCalss; //插件的class变量
    var z = settings.zIndex, newArr = mailArr = settings.mailArr, hint = settings.textHint, text = settings.hintText, fc = settings.focusColor, bc = settings.blurColor;
    //创建邮件内部列表内容
    $.createHtml = function(str, arr, cur){
      var mailHtml = "";
      if($.isArray(arr)){
        $.each(arr, function(i, n){
          if(i === cur){
            mailHtml += '<div class="mailHover '+cf+'" id="mailList_'+i+'"><span class="'+cm+'">'+str+'</span>@'+arr[i]+'</div>';  
          }else{
            mailHtml += '<div class="mailHover '+cl+'" id="mailList_'+i+'"><span class="'+cm+'">'+str+'</span>@'+arr[i]+'</div>';  
          }
        });
      }
      return mailHtml;
    };
    //一些全局变量
    var index = -1, s;
    $(this).each(function(){
      var that = $(this), i = $(".justForJs").size(); 
      if(i > 0){ //只绑定一个文本框
        return; 
      }
      var w = that.outerWidth(), h = that.outerHeight(); //获取当前对象(即文本框)的宽高
      //样式的初始化
      that.wrap('<span style="display:inline-block;position:relative;"></span>')
        .before('<div id="mailListBox_'+i+'" class="justForJs '+cb+'" style="min-width:'+w+'px;_width:'+w+'px;position:absolute;left:-6000px;top:'+h+'px;z-index:'+z+';"></div>');
      var x = $("#mailListBox_" + i), liveValue; //列表框对象
      that.focus(function(){
        //父标签的层级
        $(this).css("color", fc).parent().css("z-index", z);  
        //提示文字的显示与隐藏
        if(hint && text){
          var focus_v = $.trim($(this).val());
          if(focus_v === text){
            $(this).val("");
          }
        }
        //键盘事件
        $(this).keyup(function(e){
          s = v = $.trim($(this).val()); 
          if(/@/.test(v)){
            s = v.replace(/@.*/, "");
          }
          if(v.length > 0){
            //如果按键是上下键
            if(e.keyCode === 38){
              //向上
              if(index <= 0){
                index = newArr.length; 
              }
              index--;
            }else if(e.keyCode === 40){
              //向下
              if(index >= newArr.length - 1){
                index = -1;
              }
              index++;
            }else if(e.keyCode === 13){
              //回车
              if(index > -1 && index < newArr.length){
                //如果当前有激活列表
                $(this).val($("#mailList_"+index).text()); 
              }
            }else{
              if(/@/.test(v)){
                index = -1;
                //获得@后面的值
                //s = v.replace(/@.*/, "");
                //创建新匹配数组
                var site = v.replace(/.*@/, "");
                newArr = $.map(mailArr, function(n){
                  var reg = new RegExp(site); 
                  if(reg.test(n)){
                    return n;  
                  }
                });
              }else{
                newArr = mailArr;
              }
            }
            x.html($.createHtml(s, newArr, index)).css("left", 0);
            if(e.keyCode === 13){
              //回车
              if(index > -1 && index < newArr.length){
                //如果当前有激活列表
                x.css("left", "-6000px");  
              }
            }
          }else{
            x.css("left", "-6000px");  
          }
        }).blur(function(){
          if(hint && text){
            var blur_v = $.trim($(this).val());
            if(blur_v === ""){
              $(this).val(text);
            }
          }
          $(this).css("color", bc).unbind("keyup").parent().css("z-index",0);
          x.css("left", "-6000px");  
           
        }); 
        //鼠标经过列表项事件
        //鼠标经过
        $(".mailHover").live("mouseover", function(){
          index = Number($(this).attr("id").split("_")[1]);  
          liveValue = $("#mailList_"+index).text();
          x.children("." + cf).removeClass(cf).addClass(cl);
          $(this).addClass(cf).removeClass(cl);
        });
      });
 
      x.bind("mousedown", function(){
        that.val(liveValue);    
      });
    });
  };
   
})(jQuery);
성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.