对于 HTML 输入值,是否可以使用 JavaScript 定义一个只接受拉丁字符(任何大小写)和所有其他键(如退格键、删除键、箭头键以及 .dot、@at)的正则表达式?是否用于事件键评估,而不是事后,这就是我需要箭头和其他键的原因。
问问题
1568 次
2 回答
0
除非您提供更多详细信息,否则我认为正则表达式不会帮助您。
我不知道你需要使用的关键事件的细节,但我给自己写了一个像字典一样的对象,在我的一个项目中运行良好,但当然它不是失败证明,而且很难做到 100%,因为那里有许多键盘布局和语言,以及 javascript 和浏览器实现中不规范的事件处理。我建议先阅读这篇文章,它对我有很大帮助http://unixpapa.com/js/key.html
我对 en-US 英语键盘的解决方法。
var Keys = { "BACKSPACE":8, "TAB":9,"ENTER":13,"SHIFT":16,"CTRL":17,"ALT":18, "PAUSEBREAK":19, "CAPSLOCK":20,"ESC":27, "SPACE":32, "PAGEUP":33, "PAGEDOWN":34, "END":35, "HOME":36, "LEFT":37, "UP":38, "RIGHT":39, "DOWN":40, "PRNTSCRN":44, "INSERT":45, "DELETE":46, "0":48, "1":49, "2":50, "3":51, "4":52, "5":53, "6":54, "7":55, "8":56, "9":57, "A":65, "B":66, "C":67, "D":68, "E":69, "F":70, "G":71, "H":72, "I":73, "J":74, "K":75, "L":76, "M":77, "N":78, "O":79, "P":80, "Q":81, "R":82, "S":83, "T":84, "U":85, "V":86, "W":87, "X":88, "Y":89, "Z":90, "WINKEY":91, "WINKEYR":92, "APPLICATION":93, "NUM0":96, "NUM1":97, "NUM2":98, "NUM3":99, "NUM4":100, "NUM5":101, "NUM6":102, "NUM7":103, "NUM8":104, "NUM9":105, "MULTIPLY":106, "ADD":107, "SUBTRACT":109, "DECIMALPOINT":110, "DIVIDE":111, "F1":112, "F2":113, "F3":114, "f4":115, "F5":116, "F6":117, "F7":118, "F8":119, "F9":120, "F10":121, "F11":122, "F12":123, "NUMLOCK":144, "SCROLLLOCK":145, "SEMICOLON":186, "EQUAL":187, "COMMA":188, "DASH":189, "PERIOD":190, "SLASH":191, "GRAVE":192, "OPENBRAKET":219, "BACKSLASH":220, "CLOSEBRAKET":221, "SINGLEQUOTE":222, "MMNEXT":176, "MMPREVIOUS":177, "MMSTOP":178, "MMPLAY":179, "MMREWIND":227, "MMFORWARD":228, "MYCOMPUTER":182, "MYCALCULATOR":183, "HELP":225, "Invalid!":0
}
你可以使用喜欢
if(event.keyCode == Keys['RIGHT']) //go right
if(event.keyCode == Keys['LEFT']) //go left
if(event.keyCode == Keys['ENTER']) //do something
if(event.keyCode == Keys['ESC'] || event.keyCode == Keys['BACKSPACE']) //exit
您提到了箭头和其他键,如果您使用键来绑定游戏之类的东西,请避免使用诸如 CTRL ALT WINKEY ALTGR APPLICATION OPTION COMMAND 之类的修饰符,它们一团糟,有很多不一致之处,例如 Command 键伪装成应用程序键, 正确的 alt 作为另一个控件等,还有一些键盘没有第二个 alt 或 ctrl。所以这是一个地狱般的例外。
于 2013-01-20T05:24:07.507 回答
0
你可以使用类似的东西:
JavaScript
document.getElementById('foo').onkeydown = function (e) {
if (e.keyCode < 65 || e.keyCode > 90) {
e.preventDefault();
return false;
}
};
HTML
<textarea id="foo"></textarea>
这将限制您仅输入小写字母。它应该稍微修改一下也可以与鞋面一起使用。
于 2013-01-18T10:04:15.793 回答