如何使 html 输入具有在用户键入时保留的静态字符(输入掩码)?

How do I make a html input have static characters (input mask) that stay when the user types?

我正在尝试使我网站上的输入字段具有这样的占位符(注意:黑色字符是静态输入掩码):

如果用户在输入框中输入内容,它应该如下所示(注意:用户不必输入掩码字符):

当我尝试使用占位符属性时,文本在用户键入后消失 - 这不是我想要的。如果有像 yyyy/mm/dd hh:mm 这样的特殊语法,并且用户只能在双点(冒号)和斜线之间书写,那就更好了。

我不知道如何构建这样的东西,甚至 Google 也不明白我想说什么。

编辑: 我尝试实现的功能称为输入掩码。

如果您在项目中使用 jQuery,这应该很容易实现。

正如 David Thomas 在对您的原始问题的评论中所说,您需要使用屏蔽输入。有一个很棒的插件(如果您使用的是 jQuery),它非常容易实现,有据可查,或多或少完全符合您的要求:

http://igorescobar.github.io/jQuery-Mask-Plugin/

我知道的三种方法,但是none很实用。

在输入周围加上标签并在内容前添加 ::

<label><input type="text" /></label>

label { position: relative; }
label::before { 
    position: absolute;
    top: 0;
    z-index: 1;
    color: red;
    font-family: monospace;
    content: "[=10=]a0[=10=]a0[=10=]a0[=10=]a0/[=10=]a0[=10=]a0/[=10=]a0[=10=]a0[=10=]a0:";
}

使用多个输入,并使它们显示为一个

<div id="wrapper">
<input class="x" type="text" maxlength="4" placeholder="YYYY" />/<!--
--><input class="x" type="text" maxlength="2" placeholder="MM" />/<!--
--><input class="x" type="text" maxlength="2" placeholder="DD" />,<!--
--><input class="x" type="text" maxlength="2" placeholder="hh" />:<!--
--><input class="x" type="text" maxlength="2" placeholder="mm" />
</div>

#wrapper { display: inline-block; background-color: #FFF; border: 1px solid #000; }
.x { border: none; }
.x:first-of-type { width: 4em; }
.x:not(:first-of-type) { width: 2em; }

使用另一个"readonly"和指针事件:none绝对定位输入

<div id="wrapper2">
<input type="text" />
<input id="over" type="text" readonly value="YYYY/MM/DD hh:mm" />
</div>

#wrapper2 { position: relative; display: inline-block; }
#over { position: absolute; top: 0; pointer-events: none; background: none; opacity: 0.5; }

label { position: relative; }
label::before { 
    position: absolute;
    top: 0;
    z-index: 1;
    color: red;
    font-family: monospace;
    content: "[=13=]a0[=13=]a0[=13=]a0[=13=]a0/[=13=]a0[=13=]a0/[=13=]a0[=13=]a0[=13=]a0:";
}

#wrapper { display: inline-block; background-color: #FFF; border: 1px solid #000; }
.x { border: none; }
.x:first-of-type { width: 4em; }
.x:not(:first-of-type) { width: 2em; }

#wrapper2 { position: relative; display: inline-block; }
#over { position: absolute; top: 0; pointer-events: none; background: none; opacity: 0.5; }
<label><input type="text" /></label>

<div id="wrapper">
<input class="x" type="text" maxlength="4" placeholder="YYYY" />/<!--
--><input class="x" type="text" maxlength="2" placeholder="MM" />/<!--
--><input class="x" type="text" maxlength="2" placeholder="DD" />,<!--
--><input class="x" type="text" maxlength="2" placeholder="hh" />:<!--
--><input class="x" type="text" maxlength="2" placeholder="mm" />
</div>

<div id="wrapper2">
<input type="text" />
<input id="over" type="text" readonly value="YYYY/MM/DD hh:mm" />
</div>