gpt4 book ai didi

javascript - 表单中的手机字段

转载 作者:行者123 更新时间:2023-11-28 17:16:13 25 4
gpt4 key购买 nike

我想在我的表单中构建手机字段,如下图所示。 mobile phone field

括号有 3 位数字,下一部分也有 3 位数字,最后一部分有 4 位数字。我怎样才能实现这一目标。

最佳答案

要自己执行此操作,您需要使用上图所示的模式预先填充字段,并对keypress 事件使用react,进行相应调整。

如果当前位置的字符是“_”,则允许输入数字,否则将光标向前移动一位。

下面是一个快速但简单的示例。显然,需要更加小心地处理删除字符和单击现有电话号码,但作为示例,这应该可以帮助您继续。

magicInput.value = magicInput.placeholder;
magicInput.addEventListener("keypress", key);
magicInput.addEventListener("focus", focus);
magicInput.addEventListener("mouseup", focus);
magicInput.addEventListener("input", focus);

function key(e) {
if(!e.key.match(/\d/) || this.value.length > this.placeholder.length) {
e.preventDefault();
}
}

function focus(e) {
let i = 0;

for(i = 0; i < this.value.length; i++) {
if(this.value[i] === "_") {
break;
}
}

this.setSelectionRange(i, i + 1);
}
input {
font-size: 1.5rem;
padding: 0.5rem;
}
<input id="magicInput" type="text" name="mobile" placeholder="(___) - ___ - ____" autofocus />

关于javascript - 表单中的手机字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53431901/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com