手机号码格式化;实现手机号344格式输入:000 0000 0000

本文转自:http://blog.csdn.net/demod/article/details/78786168

DOCTYPE html>
<html lang="zh-CN">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Documenttitle>
    <style>
        body {
            position: absolute;
            left: 0;
            right: 0;
            width: 100%;
            height: 100%;
            margin: 0;
            padding: 0;
        }

        #uphone {
            box-sizing: border-box;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            -ms-transform: translate(-50%, -50%);
            -o-transform: translate(-50%, -50%);
            -webkit-transform: translate(-50%, -50%);
            -moz-transform: translate(-50%, -50%);
            border: 2px solid #ddd;
            width: 300px;
            height: 40px;
            border-radius: 10px;
            outline: none;
            padding-left: 15px;
            font-size: 18px;
        }

        #uphone:focus {
            border-left-color: #317EF3;
            border-top-color: #FF3366;
            border-bottom-color: #FF9800;
            border-right-color: #09BB07;
        }
    style>
head>

<body>
    <input id="uphone" type="tel" pattern="[0-9]*" maxlength="13" autocomplete="off" value="" placeholder="请输入您的手机号" oncontextmenu="return false"
        onpaste="return false" oncopy="return false" oncut="return false" />

    <script src="https://code.jquery.com/jquery-3.1.1.min.js">script>
    <script>
        $("#uphone").on("input propertychange", function () {
            var uphone = $(this).val();
            $(this).val(formatPhone(uphone));
            moveEnd($(this)[0]);
        });

        function formatPhone(phone_num) {
            var valueStr = phone_num.replace(/\D/g, "").substr(0, 11);
            var len = valueStr.length;
            if (len > 3 && len < 8) {
                return valueStr.substr(0, 3) + " " + valueStr.substr(3);
            } else if (len >= 8) {
                return valueStr.substr(0, 3) + " " + valueStr.substr(3, 4) + " " + valueStr.substr(7);
            }
            return valueStr;
        };

        //在部分安卓机上input的光标会在添加空格后错位,需要这个方法主动将光标放置在最后
        function moveEnd(obj) {
            //通过是否支持createTextRange判断是否是IE
            if (obj.createTextRange) {
                var rg = obj.createTextRange();
                rg.collapse(false);
                rg.select();
            } else {
                setTimeout(function () {
                    var len = obj.value.length;
                    obj.setSelectionRange(len, len);
                }, 20);
            }
        };
    script>
body>

html>

 

转载于:https://www.cnblogs.com/ssda/p/8094789.html

你可能感兴趣的:(手机号码格式化;实现手机号344格式输入:000 0000 0000)