search
HomeWeb Front-endJS Tutorialjquery implements mailbox autofill prompt function_jquery

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 the user experience, many websites will implement the automatic prompt function for email input. I have also implemented one myself. Let’s take a look at the effect first. If you think the effect is good, use it

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

page (here is a div as an 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>
<script type="text/javascript">
$("#email").mailAutoComplete({
boxClass: "out_box", //外部box样式
listClass: "list_box", //默认的列表样式
focusClass: "focus_box", //列表选样式中
markCalss: "mark_box", //高亮样式
autoClass: false,
textHint: true //提示文字自动隐藏
});
</script>

There is also some css, you may need to modify this to the color you want

<!-- 邮箱自动提示的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>

The above is all the code for jquery to implement the mailbox autofill prompt function. I hope it will be helpful to everyone's learning.

Statement
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
Replace String Characters in JavaScriptReplace String Characters in JavaScriptMar 11, 2025 am 12:07 AM

Detailed explanation of JavaScript string replacement method and FAQ This article will explore two ways to replace string characters in JavaScript: internal JavaScript code and internal HTML for web pages. Replace string inside JavaScript code The most direct way is to use the replace() method: str = str.replace("find","replace"); This method replaces only the first match. To replace all matches, use a regular expression and add the global flag g: str = str.replace(/fi

Custom Google Search API Setup TutorialCustom Google Search API Setup TutorialMar 04, 2025 am 01:06 AM

This tutorial shows you how to integrate a custom Google Search API into your blog or website, offering a more refined search experience than standard WordPress theme search functions. It's surprisingly easy! You'll be able to restrict searches to y

Build Your Own AJAX Web ApplicationsBuild Your Own AJAX Web ApplicationsMar 09, 2025 am 12:11 AM

So here you are, ready to learn all about this thing called AJAX. But, what exactly is it? The term AJAX refers to a loose grouping of technologies that are used to create dynamic, interactive web content. The term AJAX, originally coined by Jesse J

Example Colors JSON FileExample Colors JSON FileMar 03, 2025 am 12:35 AM

This article series was rewritten in mid 2017 with up-to-date information and fresh examples. In this JSON example, we will look at how we can store simple values in a file using JSON format. Using the key-value pair notation, we can store any kind

8 Stunning jQuery Page Layout Plugins8 Stunning jQuery Page Layout PluginsMar 06, 2025 am 12:48 AM

Leverage jQuery for Effortless Web Page Layouts: 8 Essential Plugins jQuery simplifies web page layout significantly. This article highlights eight powerful jQuery plugins that streamline the process, particularly useful for manual website creation

What is 'this' in JavaScript?What is 'this' in JavaScript?Mar 04, 2025 am 01:15 AM

Core points This in JavaScript usually refers to an object that "owns" the method, but it depends on how the function is called. When there is no current object, this refers to the global object. In a web browser, it is represented by window. When calling a function, this maintains the global object; but when calling an object constructor or any of its methods, this refers to an instance of the object. You can change the context of this using methods such as call(), apply(), and bind(). These methods call the function using the given this value and parameters. JavaScript is an excellent programming language. A few years ago, this sentence was

Improve Your jQuery Knowledge with the Source ViewerImprove Your jQuery Knowledge with the Source ViewerMar 05, 2025 am 12:54 AM

jQuery is a great JavaScript framework. However, as with any library, sometimes it’s necessary to get under the hood to discover what’s going on. Perhaps it’s because you’re tracing a bug or are just curious about how jQuery achieves a particular UI

10 Mobile Cheat Sheets for Mobile Development10 Mobile Cheat Sheets for Mobile DevelopmentMar 05, 2025 am 12:43 AM

This post compiles helpful cheat sheets, reference guides, quick recipes, and code snippets for Android, Blackberry, and iPhone app development. No developer should be without them! Touch Gesture Reference Guide (PDF) A valuable resource for desig

See all articles

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

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
1 months agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools