当前位置: 首页 > 编程日记 > 正文

jquery仿邮箱文本输入框自动加载邮箱后缀

jquery仿邮箱文本输入框自动加载邮箱后缀

在像百度这样的网站注册时,你会看到输入邮箱会出现自动给用户输入补全主流邮箱。这种对于增加用户体验的小例子已司空见惯。正好看到人家写的这种js功能。还挺不错,使用起来很方便,几乎不用写神呢代码。"傻瓜式式的"拿来主义"就行了。

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: 'black',              // 输入框输入提示颜色mailArr: ["@qq.com", "@gmail.com", "@126.com", "@163.com", "@hotmail.com", "@yahoo.com", "@yahoo.com.cn", "@live.com", "@sohu.com", "@sina.com", "@yeah.net", "@21cn.com"], //邮箱数组isSelectHide: true,                // 点击下拉框 是否隐藏 默认为truecallback: 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('<input type="hidden" class="hiddenCls"/>');var wrap = '<ul class="auto-tip">';for (var i = 0; i < _config.mailArr.length; i++) {wrap += '<li class="p-index' + i + '">' + '<span class="output-num"></span><em class="em" data-html="' + _config.mailArr[i] + '">' + _config.mailArr[i] + '</em></li>';}wrap += '</ul>';_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 += '<li class="p-index' + j + '">' + '<span class="output-num"></span><em class="em" data-html="' + newArrs[j] + '">' + newArrs[j] + '</em></li>';}$('.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') && $(".auto-tip", parentNode).addClass('hidden');}// 给隐藏域赋值
            $(_config.hiddenCls, parentNode).val(dataAttr);_config.callback && $.isFunction(_config.callback) && _config.callback();});}
};// 初始化
$(function () {new EmailAutoComplete({});
});
View Code

cs:

@charset "utf-8";
* {margin:0;padding:0;
}
ul, li {list-style:none;
}
.inputElem {width:198px;height:22px;line-height:22px;border:1px solid #ccc;
}
.parentCls {width:200px;height:auto; margin:0 auto;
}
.auto-tip li {width:100%;height:22px;line-height:22px;font-size:14px;
}
.auto-tip li.hoverBg {background:#ddd;cursor:pointer;
}
.red {color:#333;
}
.hidden {display:none;
}
View Code

调用如下:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /><title>主流邮箱补充提示</title><link href="css/jquery.emailAutoComplete.css" type="text/css" rel="stylesheet" /><script src="js/jquery.min.js"></script><script src="js/jquery.emailAutoComplete.js"></script>
</head><body><div class="parentCls"><input type="text" class="inputElem" /></div>
</body>
</html>
View Code

哈哈,怎么样。使用起来确实很方便。

效果演示

posted on 2014-11-18 21:52 深谷&幽兰 阅读(...) 评论(...) 编辑 收藏

转载于:https://www.cnblogs.com/fengchengjushi/p/4106832.html

相关文章:

Maven最佳实践:划分模块

所有用Maven管理的真实的项目都应该是分模块的&#xff0c;每个模块都对应着一个pom.xml。它们之间通过继承和聚合&#xff08;也称作多模块&#xff0c;multi-module&#xff09;相互关联。那么&#xff0c;为什么要这么做呢&#xff1f;我们明明在开发一个项目&#xff0c;划…

facebook 直播_什么时候是在Facebook Live上直播的最佳时间? 我分析了5,000个Facebook帖子以找出答案。...

facebook 直播by Ofir Chakon由Ofir Chakon 什么时候是在Facebook Live上直播的最佳时间&#xff1f; 我分析了5,000个Facebook帖子以找出答案。 (When is the best time to stream on Facebook Live? I analyzed 5,000 Facebook posts to find out.) Streaming on Facebook …

解决keepalived脑裂问题

检测思路&#xff1a;正常情况下keepalived的VIP地址是在主节点上的&#xff0c;如果在从节点发现了VIP&#xff0c;就设置报警信息 脚本如下&#xff1a; #!/bin/bash # 检查脑裂的脚本&#xff0c;在备节点上进行部署 LB01_VIP10.10.10.229 LB01_IP10.10.10.129 LB02_IP10.10…

iOS 根据中文字符串排序出字母索引

// 传入字符串数组 返回索引字典 - (NSDictionary *)createCharacter:(NSMutableArray *)strArr {NSMutableDictionary *dict [NSMutableDictionary dictionary];for (NSString *stringdict in strArr) {NSString *string stringdict;if ([string length]) {NSMutableString …

devops开发运维训练营_嗨,网络开发人员训练营的毕业生:这是您第一份工作需要了解的内容。...

devops开发运维训练营by Rachel Bird雷切尔伯德(Rachel Bird) 嗨&#xff0c;网络开发人员训练营的毕业生&#xff1a;这是您第一份工作需要了解的内容。 (Hey web dev bootcamp grads: Here’s what you need to know for your first job.) You worked your butt off and gai…

[bzoj1042][HAOI2008]硬币购物

有三种硬币&#xff0c;每种有自己的币值。 然后有n次询问&#xff0c;每次都给出每种硬币的数量和要付的钱s&#xff0c;求有多少种付法。n<1000 s<100000 ------ 不考虑限制&#xff0c;就是个简单dp.... 有限制的时候&#xff0c;我们可以考虑反过来用总的方案数量剪掉…

Windows netstat 查看端口、进程占用

目标&#xff1a;在Windows环境下&#xff0c;用netstat命令查看某个端口号是否占用&#xff0c;为哪个进程所占用. 操作&#xff1a;操作分为两步&#xff1a;&#xff08;1&#xff09;查看该端口被那个PID所占用;方法一&#xff1a;有针对性的查看端口&#xff0c;使用命令 …

iOS Named colors do not work prior to iOS 11.0问题解决

原文链接 https://stackoverflow.com/questions/48014246/named-colors-do-not-work-prior-to-ios-11-0-error-referring-to-a-storyboard/52967313#52967313 1 打开对应文件source code 2 粘贴查找 使用正则表达式 color key(.*) name.* 3 用以下代码覆盖 color key$1 …

如何在StackOverflow上获得第一个标签徽章-以及为什么它很重要。

by Angelos Chalaris通过安吉洛斯查拉利斯(Angelos Chalaris) 如何在StackOverflow上获得第一个标签徽章-以及为什么它很重要。 (How to get your first tag badge on StackOverflow — and why it’s important.) Every developer uses StackOverflow in different ways. Som…

int数据类型

1 a 18862 # 取商和余数3 print(a.__divmod__(10)) 4 5 # r反转,想当于 10-18866 print(a.__rsub__(10)) 7 8 # 取绝对值9 print(a.__abs__(), abs(a)) 10 11 #商取整 12 print(a.__floordiv__(10), a // 10) 转载于:https://www.cnblogs.com/xh4528/p/6497629.html

使用Google 官方的控件SwipeRefreshLayout实现下拉刷新功能

之前做东西的时候&#xff0c;经常会用到下拉刷新的功能&#xff0c;之前大家都在使用Github上的一个很著名的开源项目 PullToRefresh 但是&#xff0c;现在好消息来了&#xff0c;google在19.1版本的support-v4兼容包下面正式提供了官方的下拉刷新组件——SwipeRefreshLayout…

iOS 没到年底NSDate 时间出错问题

NSDate *currentDate [NSDate date];//获取当前时间&#xff0c;日期 NSDateFormatter *dateFormatter [[NSDateFormatter alloc] init]; [dateFormatter setDateFormat:"yyyy-MM-dd HH:mm:ss"]; // [dateFormatter setDateFormat:"YYYY-MM…

react 统一字段验证_如何使用React的受控输入进行即时表单字段验证

react 统一字段验证by Gosha Arinich通过Gosha Arinich 如何使用React的受控输入进行即时表单字段验证 (How to use React’s controlled inputs for instant form field validation) Controlled inputs enable simple things, like disabling the Submit button when some fi…

UISearchBar和 UISearchDisplayController的使用

感觉好多文章不是很全面&#xff0c;所以本文收集整合了网上的几篇文章&#xff0c;感觉有互相补充的效果。 如果想下载源码来看&#xff1a;http://code4app.com/search/searchbar 。本源码与本文无关 1、searchBar 本例子实现布局&#xff1a;上面是一个navigationController…

iOS 获取指定时间的前后N个月

https://www.cnblogs.com/SUPER-F/p/7298548.html 正数为后 负数为前 -(NSDate *)getPriousorLaterDateFromDate:(NSDate *)date withMonth:(NSInteger)month { NSDateComponents *comps [[NSDateComponents alloc] init]; [comps setMonth:month]; NSCalendar *calender …

JS高级程序设计第五章读书笔记

1.引用类型的值&#xff08;对象&#xff09;是引用类型的一个实例。在ES中&#xff0c;引用类型是一种数据结构&#xff0c;用于将数据和功能组织在一起。它们也长被称为类&#xff0c;但这并不妥当。因为ES在技术层面上是一门面对对象的语言&#xff0c;但它并不具备传统的面…

使用Tape和Vue Test Utils编写快速的Vue单元测试

by Edd Yerburgh埃德耶堡(Edd Yerburgh) 使用Tape和Vue Test Utils编写快速的Vue单元测试 (Write blazing fast Vue unit tests with Tape and Vue Test Utils) Tape is the fastest framework for unit testing Vue components.磁带是用于Vue组件进行单元测试的最快框架。 I…

js去除数组中重复值

//第三种方法加强版 Array.prototype.distinctfunction(){ var sameObjfunction(a,b){ var tag true; if(!a||!b)return false; for(var x in a){ if(!b[x]) return false; if(typeof(a[x])object){ tagsameObj(a[x],b[x]); }else{ if(a[x]!b[x]) return false; } } return ta…

CXFServlet类的作用

CXFServlet是Apache CXF框架中的一个核心组件,用于处理HTTP请求并将它们转换为Web服务调用。通过配置CXFServlet,你可以轻松地部署和管理SOAP和RESTful Web服务。

了解jvm对编程的帮助_这是您对社会责任编程的了解

了解jvm对编程的帮助by ?? Anton de Regt由?? 安东德雷格 这是您对社会责任编程的了解 (This is what you need to know about Socially Responsible Programming) 您的才华比银行帐户中的零值多 (Your talent is worth more than lots of zeroes in your bank account) L…

解压和生成 system.imgdata.img ( ext4格式)

另一篇文章讲述了如何解压和生成system.img&#xff0c; 那是针对yaffs2格式的文件系统镜像。 目前越来越多的Android手机放弃了nand, 更多采用了emmc为内部存储设备。 以emmc为存储设备的android手机&#xff0c;其文件系统(/system,/data两个分区&#xff09;一般采用ext4格式…

简单分析beyond作曲

本人绝对是业余的哈 业余到什么水平呢&#xff1f;正在练习爬格子&#xff0c;还是一个星期练几次那种 先说下《海阔天空》 6&#xff0c;5&#xff0c;4&#xff0c;3 1&#xff0c;2&#xff0c;3&#xff0c;4 简单是简单得不得了&#xff0c;声从低到高&#xff0c;然后再从…

1 OC 对象的本质(一个NSObject 对象占用的内存大小)

1 前言 目录 1 前言 2 一个NSObject占用多少内存 3 为什么呢 &#xff1f; 4 如何在内存中看呢&#xff1f; OC 的面向对象都是基于C/C 的数据结构实现的 结构体 2 clang 命令转换成c 代码 clang -rewrite-objc main.m -o main.cpp 以上的命令是不分平台进行编译的&…

Xiki:一个开发人员寻求增强命令行界面的能力

by Craig Muth通过克雷格穆斯(Craig Muth) Xiki&#xff1a;一个开发人员寻求增强命令行界面的能力 (Xiki: one developer’s quest to turbocharge the command line interface) I was sitting with my friend Charles in a trendy cafe next to Golden Gate Park in San Fra…

2 OC 对象的本质(一个Student 占用的内存大小)

一 Student 占用的内存空间 补充&#xff1a; 1 成员变量占用字节的大小&#xff1a; 2 内存对齐的规则&#xff1a;结构体的内存大小必须是最大成员变量的内存的倍数。 一个 Student 类,继承自NSObject&#xff0c;有两个属性&#xff0c;首先要知道&#xff0c;int 类型占用…

jdk动态代理源码学习

最近用到了java的动态代理&#xff0c;虽然会用&#xff0c;但不了解他具体是怎么实现&#xff0c;抽空看看了看他的源码。 说到Java的动态代理就不能不说到代理模式&#xff0c;动态代理也就是多了一个’动态’两字,在《大话设计模式》中不是有这句话吗&#xff1f;“反射&…

20162313苑洪铭 第一周作业

20162313苑洪铭 20016-2017-2 《程序设计与数据结构》第1周学习总结 教材学习内容总结 本周观看教材绪论 主要在教我建立一个简单的java程序 内容是林肯的名言 虽然看起来很简单 但是实际上问题重重 总而言之 这一周全是在出现故障的 教材学习中的问题和解决过程 教材学习好像并…

测试驱动开发 测试前移_测试驱动的开发可能看起来是工作的两倍-但无论如何您都应该这样做...

测试驱动开发 测试前移by Navdeep Singh通过Navdeep Singh 测试驱动的开发可能看起来是工作的两倍-但无论如何您都应该这样做 (Test-driven development might seem like twice the work — but you should do it anyway) Isn’t Test Driven Development (TDD) twice the wor…

3 OC 属性和方法

1 OC 的属性的生成 interface Student:NSObject {publicint _no;int _age;}property (nonatomic,assign)int height;end 当我们使用property 的时候&#xff0c;那么系统会自动的在其内部生成个属性 xcrun -sdk iphoneos clang -arch arm64 -rewrite-objc main.m -o main.c…