原理很简单,就是隐藏一个显示格式化的模块,当输入框获取焦点时显示,失去焦点时隐藏即可。
页面代码:
<div class="inputCard-wrap"> <input type="text" class="inputCard"> <div class="panelCard"></div> </div> <style type="text/css"> .inputCard-wrap{ position: relative; } .inputCard-wrap .panelCard{ display: none; position: absolute; top:-34px; left:0; z-index: 100; background-color:#fff9da; border:1px #ffce6e solid; padding:10px; height:40px; font-size: 1.7em; line-height:18px; color:#585858; } </style>
格式化代码:
/* 银行卡号实时验证放大显示 */ $(".inputCard").keyup(function(e){ var self = $.trim(e.target.value), parent = $(e.target).closest(".inputCard-wrap"), panel = $(".panelCard", parent), val = self.replace(/\D/g, ‘‘); if(self.length > 18){ this.value = self.substr(0, 18); return this.value; } if(val == self){ panel.show(); val = self.replace(/(....)(?=.)/g, ‘$1 ‘); panel.html(val); }else{ panel.hide(); return self; } }); $(".inputCard").unbind(‘focusin‘); $(".inputCard").bind(‘focusin‘,function(e){ var self = $.trim(e.target.value), parent = $(e.target).closest(".inputCard-wrap"), panel = $(".panelCard", parent), val = self.replace(/(....)(?=.)/g, ‘$1 ‘); if(val != ‘‘) { panel.show(); panel.html(val); } }); $(".inputCard").unbind(‘focusout‘); $(".inputCard").bind(‘focusout‘,function(e){ var parent = $(e.target).closest(".inputCard-wrap"), panel = $(".panelCard", parent); panel.hide(); });
/* 银行卡号实时验证放大显示 */
$(
".inputCard"
).keyup(
function
(e){
var
self = $.trim(e.target.value),
parent = $(e.target).closest(
".inputCard-wrap"
),
panel = $(
".panelCard"
, parent),
val = self.replace(/\D/g,
‘‘
);
if
(self.length > 18){
this
.value = self.substr(0, 18);
return
this
.value;
}
if
(val == self){
panel.show();
val = self.replace(/(....)(?=.)/g,
‘$1 ‘
);
panel.html(val);
}
else
{
panel.hide();
return
self;
}
});
$(
".inputCard"
).unbind(
‘focusin‘
);
$(
".inputCard"
).bind(
‘focusin‘
,
function
(e){
var
self = $.trim(e.target.value),
parent = $(e.target).closest(
".inputCard-wrap"
),
panel = $(
".panelCard"
, parent),
val = self.replace(/(....)(?=.)/g,
‘$1 ‘
);
if
(val !=
‘‘
) {
panel.show();
panel.html(val);
}
});
$(
".inputCard"
).unbind(
‘focusout‘
);
$(
".inputCard"
).bind(
‘focusout‘
,
function
(e){
var
parent = $(e.target).closest(
".inputCard-wrap"
),
panel = $(
".panelCard"
, parent);
panel.hide();
});