<bdo id='a6lUi'></bdo><ul id='a6lUi'></ul>

<small id='a6lUi'></small><noframes id='a6lUi'>

  1. <tfoot id='a6lUi'></tfoot>

    1. <legend id='a6lUi'><style id='a6lUi'><dir id='a6lUi'><q id='a6lUi'></q></dir></style></legend>

      <i id='a6lUi'><tr id='a6lUi'><dt id='a6lUi'><q id='a6lUi'><span id='a6lUi'><b id='a6lUi'><form id='a6lUi'><ins id='a6lUi'></ins><ul id='a6lUi'></ul><sub id='a6lUi'></sub></form><legend id='a6lUi'></legend><bdo id='a6lUi'><pre id='a6lUi'><center id='a6lUi'></center></pre></bdo></b><th id='a6lUi'></th></span></q></dt></tr></i><div id='a6lUi'><tfoot id='a6lUi'></tfoot><dl id='a6lUi'><fieldset id='a6lUi'></fieldset></dl></div>

      使用纯 JavaScript 将电话号码格式化为用户类型

      时间:2023-05-29
      • <tfoot id='rf62s'></tfoot>

          <small id='rf62s'></small><noframes id='rf62s'>

            <tbody id='rf62s'></tbody>
          <i id='rf62s'><tr id='rf62s'><dt id='rf62s'><q id='rf62s'><span id='rf62s'><b id='rf62s'><form id='rf62s'><ins id='rf62s'></ins><ul id='rf62s'></ul><sub id='rf62s'></sub></form><legend id='rf62s'></legend><bdo id='rf62s'><pre id='rf62s'><center id='rf62s'></center></pre></bdo></b><th id='rf62s'></th></span></q></dt></tr></i><div id='rf62s'><tfoot id='rf62s'></tfoot><dl id='rf62s'><fieldset id='rf62s'></fieldset></dl></div>

          • <bdo id='rf62s'></bdo><ul id='rf62s'></ul>

              1. <legend id='rf62s'><style id='rf62s'><dir id='rf62s'><q id='rf62s'></q></dir></style></legend>
                本文介绍了使用纯 JavaScript 将电话号码格式化为用户类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

                问题描述

                限时送ChatGPT账号..

                我的文档正文中有一个输入字段,我需要在用户键入时对其进行格式化.它应该在区号周围加上括号,然后在三到四位数字之间加上一个破折号.

                I've got an input field in the body of my document, and I need to format it as the user types. It should have parenthesis around the area code and a dash between the three and four digits after that.

                例如:(123) 456 - 7890

                当用户键入时,它应该类似于:

                As the user types it should look something like:

                (12
                (123)
                (123) 456
                (123) 456 - 78
                (123) 456 - 7890

                推荐答案

                新的 ES6 答案

                您仍然可以使用一些简单的 JavaScript 来做到这一点.

                HTML

                New ES6 Answer

                You can still do this using some simple JavaScript.

                HTML

                <input id="phoneNumber" maxlength="16" />
                

                JavaScript (ES6)

                const isNumericInput = (event) => {
                    const key = event.keyCode;
                    return ((key >= 48 && key <= 57) || // Allow number line
                        (key >= 96 && key <= 105) // Allow number pad
                    );
                };
                
                const isModifierKey = (event) => {
                    const key = event.keyCode;
                    return (event.shiftKey === true || key === 35 || key === 36) || // Allow Shift, Home, End
                        (key === 8 || key === 9 || key === 13 || key === 46) || // Allow Backspace, Tab, Enter, Delete
                        (key > 36 && key < 41) || // Allow left, up, right, down
                        (
                            // Allow Ctrl/Command + A,C,V,X,Z
                            (event.ctrlKey === true || event.metaKey === true) &&
                            (key === 65 || key === 67 || key === 86 || key === 88 || key === 90)
                        )
                };
                
                const enforceFormat = (event) => {
                    // Input must be of a valid number format or a modifier key, and not longer than ten digits
                    if(!isNumericInput(event) && !isModifierKey(event)){
                        event.preventDefault();
                    }
                };
                
                const formatToPhone = (event) => {
                    if(isModifierKey(event)) {return;}
                
                    const input = event.target.value.replace(/D/g,'').substring(0,10); // First ten digits of input only
                    const areaCode = input.substring(0,3);
                    const middle = input.substring(3,6);
                    const last = input.substring(6,10);
                
                    if(input.length > 6){event.target.value = `(${areaCode}) ${middle} - ${last}`;}
                    else if(input.length > 3){event.target.value = `(${areaCode}) ${middle}`;}
                    else if(input.length > 0){event.target.value = `(${areaCode}`;}
                };
                
                const inputElement = document.getElementById('phoneNumber');
                inputElement.addEventListener('keydown',enforceFormat);
                inputElement.addEventListener('keyup',formatToPhone);
                

                如果你想摆弄它:
                https://jsfiddle.net/rafj3md0/

                免责声明:
                值得注意的是,如果您尝试修改数字的中间,这会有点奇怪,因为浏览器在设置元素值后处理插入符号位置的方式.解决这个问题是可行的,但需要比我现在更多的时间,而且有一些图书馆可以处理这样的事情.

                Disclaimer:
                It's worth noting this gets a little weird if you attempt to modify the middle of the number because of the way browsers handle caret placement after you set an element's value. Solving that problem is doable, but would require more time than I have right now, and there are libraries out there that handle things like that.

                如果您的 HTML 看起来像:
                <输入类型=文本"id="phoneNumber"/>

                If your HTML looks like:
                <input type="text" id="phoneNumber"/>

                您的 JavaScript 函数可以是:

                Your JavaScript function can simply be:

                // A function to format text to look like a phone number
                function phoneFormat(input){
                        // Strip all characters from the input except digits
                        input = input.replace(/D/g,'');
                        
                        // Trim the remaining input to ten characters, to preserve phone number format
                        input = input.substring(0,10);
                
                        // Based upon the length of the string, we add formatting as necessary
                        var size = input.length;
                        if(size == 0){
                                input = input;
                        }else if(size < 4){
                                input = '('+input;
                        }else if(size < 7){
                                input = '('+input.substring(0,3)+') '+input.substring(3,6);
                        }else{
                                input = '('+input.substring(0,3)+') '+input.substring(3,6)+' - '+input.substring(6,10);
                        }
                        return input; 
                }
                

                当然,您需要一个事件监听器:

                Of course, you'll need an event listener:

                document.getElementById('phoneNumber').addEventListener('keyup',function(evt){
                        var phoneNumber = document.getElementById('phoneNumber');
                        var charCode = (evt.which) ? evt.which : evt.keyCode;
                        phoneNumber.value = phoneFormat(phoneNumber.value);
                });
                

                除非您可以将电话号码存储为格式化字符串(我不推荐这样做),否则您需要在提交值之前清除非数字字符:
                document.getElementById('phoneNumber').value.replace(/D/g,'');

                And unless you're okay storing phone numbers as formatted strings (I don't recommend this), you'll want to purge the non-numeric characters before submitting the value with something like:
                document.getElementById('phoneNumber').value.replace(/D/g,'');

                如果您想通过奖励输入过滤查看此操作,请查看此小提琴:
                http://jsfiddle.net/rm9vg16m/

                If you'd like to see this in action with bonus input filtering, check out this fiddle:
                http://jsfiddle.net/rm9vg16m/

                // Format the phone number as the user types it
                document.getElementById('phoneNumber').addEventListener('keyup', function(evt) {
                  var phoneNumber = document.getElementById('phoneNumber');
                  var charCode = (evt.which) ? evt.which : evt.keyCode;
                  phoneNumber.value = phoneFormat(phoneNumber.value);
                });
                
                // We need to manually format the phone number on page load
                document.getElementById('phoneNumber').value = phoneFormat(document.getElementById('phoneNumber').value);
                
                // A function to determine if the pressed key is an integer
                function numberPressed(evt) {
                  var charCode = (evt.which) ? evt.which : evt.keyCode;
                  if (charCode > 31 && (charCode < 48 || charCode > 57) && (charCode < 36 || charCode > 40)) {
                    return false;
                  }
                  return true;
                }
                
                // A function to format text to look like a phone number
                function phoneFormat(input) {
                  // Strip all characters from the input except digits
                  input = input.replace(/D/g, '');
                
                  // Trim the remaining input to ten characters, to preserve phone number format
                  input = input.substring(0, 10);
                
                  // Based upon the length of the string, we add formatting as necessary
                  var size = input.length;
                  if (size == 0) {
                    input = input;
                  } else if (size < 4) {
                    input = '(' + input;
                  } else if (size < 7) {
                    input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6);
                  } else {
                    input = '(' + input.substring(0, 3) + ') ' + input.substring(3, 6) + ' - ' + input.substring(6, 10);
                  }
                  return input;
                }

                Enter a phone number here: <input type="text" id="phoneNumber" onkeypress="return numberPressed(event);" />

                这篇关于使用纯 JavaScript 将电话号码格式化为用户类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持html5模板网!

                上一篇:用于在 JavaScript 中格式化数字的正则表达式 下一篇:jquery嵌套ajax调用格式化

                相关文章

                最新文章

              2. <tfoot id='7aeES'></tfoot>

              3. <small id='7aeES'></small><noframes id='7aeES'>

                1. <legend id='7aeES'><style id='7aeES'><dir id='7aeES'><q id='7aeES'></q></dir></style></legend>

                    <i id='7aeES'><tr id='7aeES'><dt id='7aeES'><q id='7aeES'><span id='7aeES'><b id='7aeES'><form id='7aeES'><ins id='7aeES'></ins><ul id='7aeES'></ul><sub id='7aeES'></sub></form><legend id='7aeES'></legend><bdo id='7aeES'><pre id='7aeES'><center id='7aeES'></center></pre></bdo></b><th id='7aeES'></th></span></q></dt></tr></i><div id='7aeES'><tfoot id='7aeES'></tfoot><dl id='7aeES'><fieldset id='7aeES'></fieldset></dl></div>
                    • <bdo id='7aeES'></bdo><ul id='7aeES'></ul>