手机号格式化显示插件 —— 菜鸟造轮子
创建时间:2018/7/12
最后更新时间:2018/7/12
主要内容:
菜鸟日常造轮子,一个用于显示格式化手机号的插件
菜鸟在做页面时需要添加一个让字符串格式化显示的工具来减少输入时可能的错误,算是用户体验的一部分吧,于是造了个轮子,学习不久还有很多不懂的,如果有什么改进的意见欢迎提出
效果:
源代码:(方便阅读js和css都写在了html里)
<!--
Create Time:2018/7/12
Description:Formatting number plugin
Author:HZH
-->
<!DOCTYPE html>
<html>
<head>
<title></title>
<meta charset="utf-8">
<script type="text/javascript" src="https://cdn.bootcss.com/jquery/1.10.2/jquery.min.js"></script>
<style>
div.phone_show_box{position:relative; height: 0;}
p.phone_show{
background: #eee;
padding:10px;
bottom:0;
white-space: pre;
position: absolute;
border: 3px solid #ccc;
font-weight: 700;
font-size: x-large;
margin: 0;
}
p.hide{visibility: hidden}
</style>
<script>
//为拥有类名:tel_show的input添加手机号码的框框
function init_phone_show() {
// 为所有的tel_show前面添加一个phone_show_box
// 这里我考虑过在点击时才动态用before添加一个div在前面,但是实际不知道哪个方式更好,
// 目前做法是在加载js时就把页面中所有的input.tel_show前面都加上一个div.phone_show_box来显示数字
// 我感觉我加载时这样写会导致大量的重绘甚至回流问题
// 但不知道有什么其他方法就先这样吧
(function add_phone_show_box() {
var template = ('<div class="phone_show_box"><p class="phone_show hide"></p></div>');
var tels = $(".tel_show");
for(var idx=0,len=tels.length;idx<len;idx++)
{
tels[idx].before($(template).get(0));
}
})();
//将长度为0到11位的手机号格式化(不符合校验规则时报错)
function getsplit(numstr){
if(!/^1\d{0,10}$/.test(numstr)){
return "手机号格式错误!"
}
return numstr.substring(0,3)+" "+numstr.substring(3,7)+" "+numstr.substring(7,11);
}
//为tel_show这个类添加监听函数,来显示对应的
(function addEventListener_to_tel_show() {
var tels = document.getElementsByClassName("tel_show");
var phone_shows = document.getElementsByClassName("phone_show");
function change_tel(e,idx_in) {
var tel_number = e.target.value.replace(/[^\d]/g,"");//去除空格和非数字
phone_shows[idx_in].innerText=getsplit(tel_number);
}
for(var idx = 0,len=tels.length; idx<len; idx++){
/*
这里的监听函数都用到了立即执行的匿名函数 function(idx){...}(idx)
把原有的函数给包裹起来了,用来传递循环变量idx,
如果不用这样话会函数内部会引用了到了可能改变的变量idx,会导致所有的监听函数的idx都为 len+1,即跳出循环时idx最终的值
这个匿名函数的返回值是一个函数
这里所返回的函数的参数依然是event
备注:这个问题是 idea 提示我的,不然就有bug了...看不懂的话百度一下:循环变量 闭包
update:为了清晰起见把内部的参数名称修改一下更方便理解 function(idx_in){...}(idx)
Q:我这样做用闭包会不会导致什么问题?
*/
//松开按键时更新text
tels[idx].addEventListener("keyup",function (idx_in){
return function (e) {
change_tel(e,idx_in);
};
}(idx));
//获得焦点时显示
tels[idx].addEventListener("focus",function (idx_in){
return function (e) {
change_tel(e,idx_in);
phone_shows[idx_in].classList.remove("hide");
};
}(idx));
//失去焦点时隐藏
tels[idx].addEventListener("blur",function (idx_in){
return function () {
phone_shows[idx_in].classList.add("hide");
};
}(idx));
}
})();
}
$(function(){
init_phone_show();
})
</script>
</head>
<body>
<!-- 下面为示例 -->
<div style="position: relative;top: 100px;">
<input type="text" name="tel_phone" class="tel_show" placeholder="在此输入手机" >
</div>
</body>
</html>
使用方式: 为input添加class:tel_show
<input type="text" name="tel_phone" class="tel_show" placeholder="在此输入手机" >
代码内容:
- 为所有的tel_show前面添加一个div.show
- 为tel_show绑定监听函数(focus,blur,keyup)来改变对应的phone_show_box中的内容