将html文本框屏蔽为美国电话号码格式

时间:2018-07-25 03:51:23

标签: javascript c# html

我使用以下代码进行屏蔽。

但是问题出在光标的位置。

HTML

JS

Array.prototype.forEach.call(document.body.querySelectorAll(“ * [数据掩码]”),applyDataMask);

function applyDataMask(field){     var mask = field.dataset.mask.split('');

// For now, this just strips everything that's not a number
function stripMask(maskedData) {
    function isDigit(char) {
        return /\d/.test(char);
    }
    return maskedData.split('').filter(isDigit);
}

// Replace `_` characters with characters from `data`
function applyMask(data) {
    return mask.map(function (char) {
        if (char != '_') return char;
        if (data.length == 0) return char;
        return data.shift();
    }).join('')
}

function reapplyMask(data) {
    return applyMask(stripMask(data));
}

function changed() {
    var oldStart = field.selectionStart;
    var oldEnd = field.selectionEnd;
    field.value = reapplyMask(field.value);
    field.selectionStart = oldStart;
    field.selectionEnd = oldEnd;
}

field.addEventListener('click', changed)
field.addEventListener('keyup', changed)

}

1 个答案:

答案 0 :(得分:0)

HTML:

<input id="txtPhone" data-mask="(___) ___-____" type="text" />

JavaScript:

 Array.prototype.forEach.call(document.body.querySelectorAll("*[data-mask]"), applyDataMask);

 function applyDataMask(field) {

    var mask = field.dataset.mask.split('');

    // For now, this just strips everything that's not a number
    function stripMask(maskedData) {
        function isDigit(char) {
            return /\d/.test(char);
        }
        return maskedData.split('').filter(isDigit);
    }

    // Replace `_` characters with characters from `data`
    function applyMask(data) {
        return mask.map(function (char) {
            if (char != '_') return char;
            if (data.length == 0) return char;
            return data.shift();
        }).join('')
    }

    function reapplyMask(data) {
        return applyMask(stripMask(data));
    }

    function changed(e) {
        var i = field.value.indexOf('_');
        if (e.keyCode == undefined) {
            i = 0;
        }
        field.value = reapplyMask(field.value);
        field.selectionStart = i;
        field.selectionEnd = i;
    }

    field.addEventListener('click', changed)
    field.addEventListener('keyup', changed);
}