在HTML(5)文本输入中屏蔽字符的最简单方法 [英] Easiest way to mask characters in HTML(5) text input
问题描述
HTML5是否有任何类型的文本字段屏蔽,还是我仍然需要捕获 onkeydown
等?
Does HTML5 have any kind of text field masking or do I still have to trap onkeydown
etc.?
jbabey是对的 - 屏蔽就像阻止某些非法字符一样,而不是隐藏所输入的内容。
jbabey is right--"masking" as in blocking certain illegal characters, not hiding what's typed.
我最好的方式(最简单,最可靠)发现是捕获 onkeyup
,然后只对文本字段的值运行正则表达式替换,删除任何非法字符。
The best (as in simplest and most reliable) way I've found is to trap onkeyup
and then just run a regex replace on the value of the textfield, removing any illegal characters.
这有一些优点:
- 它很容易实现(一个函数,两行代码)。
- 这是可靠的,涵盖了我所想过的所有情况。
- 它不会阻止复制/粘贴等关键命令,选择全部或箭头键。
但它的主要缺点是它在删除之前会短暂显示打字字符,这使得它看起来非常hackish和unprofessional。
But its major disadvantage is it shows the typed character(s) briefly before removing them, which makes it look very hackish and unprofessional.
推荐答案
查找新的 HTML5输入类型。这些指示浏览器执行客户端数据过滤,但实现在不同浏览器中是不完整的。 模式
属性将执行正则表达式样式过滤,但同样,浏览器不会完全(或根本)支持它。
Look up the new HTML5 Input Types. These instruct browsers to perform client-side filtering of data, but the implementation is incomplete across different browsers. The pattern
attribute will do regex-style filtering, but, again, browsers don't fully (or at all) support it.
但是,这些不会阻止输入本身,它只会阻止使用无效数据提交表单。您仍然需要捕获 onkeydown
事件,以便在屏幕上显示之前阻止键输入。
However, these won't block the input itself, it will simply prevent submitting the form with the invalid data. You'll still need to trap the onkeydown
event to block key input before it displays on the screen.
这篇关于在HTML(5)文本输入中屏蔽字符的最简单方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!