0

我需要用 javascript 在字段中放置一个掩码。例如:+55 (11) 98888-0000 或 +55 (11) 8888-0000。

我有一个像 (11) 99999-9999 或 (11) 9999-9999 一样工作的 javascript 函数,我需要修改它以离开上面的示例。这是功能代码。

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Mascara Telefone</title>
 </head>
 <body>
  <html>
<head>
    <title>Mascara Telefone</title>
<script type="text/javascript">
/* Máscaras ER */
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}
function mtel(v){
    v=v.replace(/\D/g,"");                  // Removes all non-digit
    v=v.replace(/^(\d{2})(\d)/g,"($1) $2"); // Place parentheses around the first two digits
    v=v.replace(/(\d)(\d{4})$/,"$1-$2");    // Places hyphen between the fourth and fifth digits
    return v;
}
function id( el ){
	return document.getElementById( el );
}
window.onload = function(){
	id('telefone').onkeyup = function(){
		mascara( this, mtel );
	}
}
</script>

</head>
<body>
    <input type="text" name="telefone" id="telefone" maxlength="15" />

</body>
</html>
 </body>
</html>

4

1 回答 1

0

您可以根据函数输入文本的长度指定条件

对于 +55 (11) 8888-0000 这个使用下面 exp v=v.replace(/^(\d{2})(\d{2})(\d{4})(\d)/g," +"+"$1 ($2) $3-$4"); 和最大长度= 18

对于 +55 (11) 98888-0000 使用下面的 exp v=v.replace(/^(\d{2})(\d{2})(\d{5})(\d)/g,"+ "+"$1 ($2) $3-$4");并且最大长度=19

<!doctype html>
<html lang="en">
 <head>
  <meta charset="UTF-8">
  <meta name="Generator" content="EditPlus®">
  <meta name="Author" content="">
  <meta name="Keywords" content="">
  <meta name="Description" content="">
  <title>Mascara Telefone</title>
 </head>
 <body>
  <html>
<head>
    <title>Mascara Telefone</title>
<script type="text/javascript">
/* Máscaras ER */
function mascara(o,f){
    v_obj=o
    v_fun=f
    setTimeout("execmascara()",1)
}
function execmascara(){
    v_obj.value=v_fun(v_obj.value)
}
function mtel(v){
    v=v.replace(/\D/g,"");                  // Removes all non-digit
    v=v.replace(/^(\d{2})(\d{2})(\d{5})(\d)/g,"+"+"$1 ($2) $3-$4");
    return v;
}
function id( el ){
	return document.getElementById( el );
}
window.onload = function(){
	id('telefone').onkeyup = function(){
		mascara( this, mtel );
	}
}
</script>

</head>
<body>
    <input type="text" name="telefone" id="telefone" maxlength="19" />

</body>
</html>
 </body>
</html>

于 2017-10-10T13:27:20.027 回答