Skip to content
On this page

🐐 手机号输入自动调整格式

在工作中,偶尔会有用户输入手机号自动调整格式的业务,接下来这个案例给大家复现一下,此篇文章若有疑惑不解之处,欢迎打扰 作者联系微信 Akaibiu (烦请备注说明来意,谢谢)

html
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
  <meta name="renderer" content="webkit" />
  <title>Title</title>
</head>

<body>
  <input type="text" id="telphone" /><span id="err"></span>
  <script>
    var telphone = document.getElementById("telphone");
    var err = document.getElementById("err");
    //定义两个缓存值
    var firstLen = 0;
    var lastLen = 0;
    var re = /^1(3|4|5|7|8)\d{9}$/;
    telphone.oninput = function () {
      telphone.value = telphone.value.substr(0, 13); //只允许输入11位+2个空格
      //用户输入满11位开始验证
      if (telphone.value.length == 13) {
        //将数据去掉空格后验证
        if (!re.test(telphone.value.replace(/\s/g, ""))) {
          err.innerHTML = "手机号码有误";
        } else {
          err.innerHTML = "";
        }
      } else {
        err.innerHTML = "";
      }
    };
    telphone.onfocus = function () {
      timer = setInterval(function () {
        lastLen = telphone.value.length;
        if (lastLen > firstLen) {
          firstLen = telphone.value.length;
          if (lastLen === 4 || lastLen === 9) {
            var temp1 = telphone.value.substr(0, telphone.value.length - 1);
            var temp2 = telphone.value.substr(telphone.value.length - 1);
            telphone.value = temp1 + " " + temp2;
          }
        } else if (lastLen <= firstLen) {
          if (lastLen === 4 || lastLen === 9) {
            telphone.value = telphone.value.substr(
              0,
              telphone.value.length - 1
            );
          }
          firstLen = telphone.value.length;
        }
      }, 10); //如果手机出现卡顿,可适当把定时器时间加大
    };
  </script>
</body>

</html>

alt 示例图片

  • 好了,以上的总结就到此为止了,如果有疑问可以不问也可以联系作者。咱们下期再见! Good bye! 🌸

Released under the MIT License.