使用掩码实现输入 [英] Implement an input with a mask

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

问题描述

我想为接受日期的文本 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)

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

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆