本文介绍了用遮罩实现输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为接受日期的文本input字段实现掩码.屏蔽的值应直接显示在input内部.

I would like to implement a mask for a text input field which accepts a date. The masked value should display directly inside of the input.

类似这样的东西:

<input type='text' value='____/__/__'>

在该示例中,我将掩码写为值,但是我的目的是允许人们写日期而无需键入/-来分隔月份,年份和日期.用户应该能够在显示的字段中输入数字,而掩码会在用户键入时自动强制采用格式.

I wrote the mask as a value in that example, but my intent is to allow people to write a date without typing / or - to separate months, years and days. The user should be able to enter numbers into the displayed field, while the mask enforces the format automatically as the user types.

我在其他站点上也看到过这种行为,但是我不知道它是如何工作的或如何自己实现.

I have seen this behavior on other sites, but I have no idea how it works or how to implement it myself.

推荐答案

可以使用 keyup 事件,而 HTMLInputElement valueselectionStartselectionEnd属性.这是一个非常简单的实现,可以完成您想要的一些事情.它当然不是完美的,但是可以很好地演示该原理:

Input masks can be implemented using a combination of the keyup event, and the HTMLInputElement value, selectionStart, and selectionEnd properties. Here's a very simple implementation which does some of what you want. It's certainly not perfect, but works well enough to demonstrate the principle:

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() {
        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)
}
ISO Date: <input type="text" value="____-__-__" data-mask="____-__-__"/><br/>
Telephone: <input type="text" value="(___) ___-____" data-mask="(___) ___-____"/><br/>

(在JSFiddle中查看)

还有许多执行此功能的库.一些示例包括:

There are also a number of libraries out there which perform this function. Some examples include:

  • jquery.inputmask
  • MASKED INPUT PLUGIN
  • Politespace (presents an alternative to input masks)

这篇关于用遮罩实现输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-30 15:04