問題描述
我的文檔正文中有一個輸入字段,我需要在用戶鍵入時對其進(jìn)行格式化.它應(yīng)該在區(qū)號周圍加上括號,然后在三到四位數(shù)字之間加上一個破折號.
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
當(dāng)用戶鍵入時,它應(yīng)該類似于:
As the user types it should look something like:
(12
(123)
(123) 456
(123) 456 - 78
(123) 456 - 7890
推薦答案
新的 ES6 答案
您仍然可以使用一些簡單的 JavaScript 來做到這一點(diǎn).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/
免責(zé)聲明:
值得注意的是,如果您嘗試修改數(shù)字的中間,這會有點(diǎn)奇怪,因?yàn)闉g覽器在設(shè)置元素值后處理插入符號位置的方式.解決這個問題是可行的,但需要比我現(xiàn)在更多的時間,而且有一些圖書館可以處理這樣的事情.
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 函數(shù)可以是:
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;
}
當(dāng)然,您需要一個事件監(jiān)聽器:
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);
});
除非您可以將電話號碼存儲為格式化字符串(我不推薦這樣做),否則您需要在提交值之前清除非數(shù)字字符: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);" />
這篇關(guān)于使用純 JavaScript 將電話號碼格式化為用戶類型的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!