Home Web Front-end JS Tutorial jquery implements the automatic completion drop-down prompt function when entering an email_javascript skills

jquery implements the automatic completion drop-down prompt function when entering an email_javascript skills

May 16, 2016 pm 03:37 PM

I remember that when I was working on a project last year, I used the automatic prompt function for email input, so I searched online and found this well written article. Now that I think about it, I reprint it for easy reference.

The widespread use of email is due to the fact that it is free, so many websites will directly use email as their account name when registering

In order to improve user experience, many websites will implement automatic prompt functions for email input.

The effect is as shown in the figure:

Core code (requires jquery support):

(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);
Copy after login

html example:

<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>

Copy after login

jquery code called:

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

Copy after login

css, you can modify it to the color you want

 <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>
Copy after login

Effect 2:

1. This plug-in is width-adaptive, that is, when the internal text is too long, the width of the external div will be automatically extended. If the width value is set when customizing CSS, width adaptation will fail in non-IE6 browsers;
2. There is no need to set the position attribute, or width and height for the outermost box in the style. The jQuery plug-in has already done this for you. Setting these attributes is not conducive to the display of the effect;
3. This plug-in can only be used on single-line text boxes. Since there are no restrictions on elements of other label types, if the binding object is incorrect, some unexpected situations may occur.
4. Welcome to raise various questions and bugs during use.
--------------------------------------------------
Note: How to use
CSS code:

.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;}
Copy after login

JS code:

$("#customTest").mailAutoComplete({
  boxClass: "out_box", //外部box样式
  listClass: "list_box", //默认的列表样式
  focusClass: "focus_box", //列表选样式中
  markCalss: "mark_box", //高亮样式
  autoClass: false,
  textHint: true, //提示文字自动隐藏
  hintText: "请输入邮箱地址"
});
Copy after login
(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);
Copy after login
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

What should I do if I encounter garbled code printing for front-end thermal paper receipts? What should I do if I encounter garbled code printing for front-end thermal paper receipts? Apr 04, 2025 pm 02:42 PM

Frequently Asked Questions and Solutions for Front-end Thermal Paper Ticket Printing In Front-end Development, Ticket Printing is a common requirement. However, many developers are implementing...

Who gets paid more Python or JavaScript? Who gets paid more Python or JavaScript? Apr 04, 2025 am 12:09 AM

There is no absolute salary for Python and JavaScript developers, depending on skills and industry needs. 1. Python may be paid more in data science and machine learning. 2. JavaScript has great demand in front-end and full-stack development, and its salary is also considerable. 3. Influencing factors include experience, geographical location, company size and specific skills.

Demystifying JavaScript: What It Does and Why It Matters Demystifying JavaScript: What It Does and Why It Matters Apr 09, 2025 am 12:07 AM

JavaScript is the cornerstone of modern web development, and its main functions include event-driven programming, dynamic content generation and asynchronous programming. 1) Event-driven programming allows web pages to change dynamically according to user operations. 2) Dynamic content generation allows page content to be adjusted according to conditions. 3) Asynchronous programming ensures that the user interface is not blocked. JavaScript is widely used in web interaction, single-page application and server-side development, greatly improving the flexibility of user experience and cross-platform development.

How to merge array elements with the same ID into one object using JavaScript? How to merge array elements with the same ID into one object using JavaScript? Apr 04, 2025 pm 05:09 PM

How to merge array elements with the same ID into one object in JavaScript? When processing data, we often encounter the need to have the same ID...

How to achieve parallax scrolling and element animation effects, like Shiseido's official website?
or:
How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? How to achieve parallax scrolling and element animation effects, like Shiseido's official website? or: How can we achieve the animation effect accompanied by page scrolling like Shiseido's official website? Apr 04, 2025 pm 05:36 PM

Discussion on the realization of parallax scrolling and element animation effects in this article will explore how to achieve similar to Shiseido official website (https://www.shiseido.co.jp/sb/wonderland/)...

The difference in console.log output result: Why are the two calls different? The difference in console.log output result: Why are the two calls different? Apr 04, 2025 pm 05:12 PM

In-depth discussion of the root causes of the difference in console.log output. This article will analyze the differences in the output results of console.log function in a piece of code and explain the reasons behind it. �...

Is JavaScript hard to learn? Is JavaScript hard to learn? Apr 03, 2025 am 12:20 AM

Learning JavaScript is not difficult, but it is challenging. 1) Understand basic concepts such as variables, data types, functions, etc. 2) Master asynchronous programming and implement it through event loops. 3) Use DOM operations and Promise to handle asynchronous requests. 4) Avoid common mistakes and use debugging techniques. 5) Optimize performance and follow best practices.

How to implement panel drag and drop adjustment function similar to VSCode in front-end development? How to implement panel drag and drop adjustment function similar to VSCode in front-end development? Apr 04, 2025 pm 02:06 PM

Explore the implementation of panel drag and drop adjustment function similar to VSCode in the front-end. In front-end development, how to implement VSCode similar to VSCode...

See all articles