如何在号码输入字段中以这种“ xxx-xxx-xxxx”格式输入电话号码

Afi*_*han 4 html javascript jquery

我希望每当我在数字输入字段中以数字XXXXXXXXXX格式输入数字时,就像XXX-XXX-XXXX使用HTML,CSS和javascript一样。

就像此代码段一样,但不使用mask脚本。

$('.phone_us').mask('000-000-0000');
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->

<input type="text" class="phone_us" />
Run Code Online (Sandbox Code Playgroud)

FZs*_*FZs 7

这里有一些可行的答案,但是这种解决方案更稳定。

  • 使用oninput事件进行即时替换和...
  • 在整个字符串上应用正则表达式,以允许复制/粘贴,最后...
  • 此代码也较短:

$('.phone_us').on('input', function() {              //Using input event for instant effect
  let text=$(this).val()                             //Get the value
  text=text.replace(/\D/g,'')                        //Remove illegal characters 
  if(text.length>3) text=text.replace(/.{3}/,'$&-')  //Add hyphen at pos.4
  if(text.length>7) text=text.replace(/.{7}/,'$&-')  //Add hyphen at pos.8
  $(this).val(text);                                 //Set the new text
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="phone_us" maxlength="12">
Run Code Online (Sandbox Code Playgroud)

甚至没有jQuery:

document.querySelector('.phone_us').addEventListener('input', function() { //Using input event for instant effect
  let text=this.value                                                      //Get the value
  text=text.replace(/\D/g,'')                                              //Remove illegal characters
  if(text.length>3) text=text.replace(/.{3}/,'$&-')                        //Add hyphen at pos.4
  if(text.length>7) text=text.replace(/.{7}/,'$&-')                        //Add hyphen at pos.8
  this.value=text;                                                         //Set the new text
});
Run Code Online (Sandbox Code Playgroud)
<input class="phone_us" maxlength="12">
Run Code Online (Sandbox Code Playgroud)

  • 我认为这是最好的答案,我要删除我的 (2认同)

Aru*_*M N 5

你可以这样尝试

   $(document).ready(function () {

$(".phone_us").keyup(function (e) {
    var value = $(".phone_us").val();
    if (e.key.match(/[0-9]/) == null) {
        value = value.replace(e.key, "");
        $(".phone_us").val(value);
        return;
    }

    if (value.length == 3) {
        $(".phone_us").val(value + "-")
    }
    if (value.length == 7) {
        $(".phone_us").val(value + "-")
    }
});
});
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<script src="https://igorescobar.github.io/jQuery-Mask-Plugin/js/jquery.mask.min.js" type="text/javascript"></script>
<!--mask script-->
 
<form id="form1" runat="server">
        <input type="text" maxlength="12" class="phone_us"/>
    </form>
Run Code Online (Sandbox Code Playgroud)