1. 程式人生 > >js手機號空格填充

js手機號空格填充

多的不說,直接上程式碼:

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>手機號空格填充</title>
<script type="text/javascript" src="https://apps.bdimg.com/libs/jquery/2.1.4/jquery.min.js"></script>
<script type="text/javascript">
    function getMoblieFormat(obj)
        {
            var value = obj.value;
            value = value.replace(/\s*/g, "");
            var result = [];
            for(var i = 0; i < value.length; i++){
                if (i==3||i==7){
                    // console.log(value.charAt(i));
                    result.push(" " + value.charAt(i));

                }else{
                    result.push(value.charAt(i));
                }
            }
            obj.value = result.join(""); 
        }
</script>
</head>
<body>
    手機號:
    <input type="text" id="tel" value="" placeholder="請輸入手機號。。。" onkeyup="getMoblieFormat(this)" maxlength="13" />
</body>
</html>

效果: