我正在编写一个jQuery插件,用于文本字段(即xxx-xxxx-xxxx)上的电话掩码。它应该非常简单——当用户键入时,只需在适当的位置插入连字符。由于各种原因,我不能使用插件。必须从头开始。我发现的唯一一个真正的插件对我的目的来说有点过于膨胀了。我目前正在做这样的事情:
var number = phoneTextbox.val().replace(/D/g, '');
var output = "";
for (var i = 0; i < number.length; i++) {
if (i == 2) {
output += number[i] + '-';
} else if (i == 5) {
output += number[i] + '-';
} else {
output += number[i];
}
}
phoneTextbox.val(output);
但当试图编辑或删除数字时,它会变得不稳定。有没有更简单的解决方案可以处理像我这样简单的用例?
编辑:我想我的"掩蔽"术语混淆了一些人。所谓屏蔽,我指的是这个插件实现的功能:http://igorescobar.github.io/jQuery-Mask-Plugin/-如果允许的话,我会使用它!
function formatPhone(p){
if (p.length !== 10){
console.warn("Invalid phone length");
return p;
}
return [p.substr(0,3), p.substr(3,3), p.substr(6,4)].join("-");
}
下面是一把小提琴,展示了它的使用方法:http://jsfiddle.net/692ckv12/
jsFiddle Demo
只需使用内置的构造进行掩蔽,并使用一些简单的javascript进行聚焦。
html
<div>
<div>Phone Number</div>
<div class="phone">
( <input type="password" maxlength="3" width="10px" /> ) <input type="password" maxlength=3 /> - <input type="password" maxlength=4 />
</div>
</div>
css
.phone input{
padding:1px;
width: 15px;
text-align:center;
}
.phone input:last-child{
width: 20px;
}
js
var inputs = document.querySelectorAll('.phone input');
for(var i = 0; i < 2; i++){
var input = inputs[i];
(function(copy){
input.oninput = function(){
if(this.value.length == this.getAttribute("maxlength")){
inputs[copy+1].focus();
}
};
})(i);
}
已经有插件允许屏蔽输入字段;没有必要重新发明轮子。例如,看看Masked Input插件(或者只是在谷歌上搜索"jquery mask Input")。