您可以使用keyCode
和/或结合使用charCode
(如果需要)。基本思想是:
- 在数组/对象中创建所有必需键码的映射
- 处理说
keydown
和听键码的事件
- 在您的地图中查找键码,如果找到则显示它
- 防止默认(以防止例如说退格浏览回来)
- 如果在地图中没有找到,让角色像往常一样通过。
一个非常基本的例子:
演示:http: //jsfiddle.net/abhitalks/L7nhZ/
相关js:
keyMap = {8:"[Backspace]",9:"[Tab]",13:"[Enter]",16:"[Shift]",17:"[Ctrl]",18:"[Alt]",19:"[Break]",20:"[Caps Lock]",27:"[Esc]",32:"[Space]",33:"[Page Up]",34:"[Page Down]",35:"[End]",36:"[Home]",37:"[Left]",38:"[Up]",39:"[Right]",40:"[Down]",45:"[Insert]",46:"[Delete]"};
$("#txt").on("keydown", function(e) {
// check if the keycode is in the map that what you want
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
// if found add the corresponding description to the existing text
this.value += keyMap[e.keyCode];
// prevent the default behavior
e.preventDefault();
}
// if not found, let the entered character go thru as is
});
编辑:(根据评论)
概念保持不变,只是将值复制到第二个输入:
演示 2:http: //jsfiddle.net/abhitalks/L7nhZ/3/
$("#txt1").on("keyup", function(e) {
if (typeof(keyMap[e.keyCode]) !== 'undefined') {
this.value += keyMap[e.keyCode];
e.preventDefault();
}
$("#txt2").val(this.value); // copy the value to the second input
});
关于删除描述,我无法通过缓存地图中最后插入的描述来完成。不知何故,我一直在用变量处理正则表达式。无论如何,一个更简单的解决方案是使用硬编码映射为 keyup 添加另一个事件处理程序。
感谢@serakfalcon for (那个简单的解决方案),我们在这里使用它:
$('#txt1').keydown(function(event) {
if(8 == event.keyCode) {
var el = $(this);
el.val(el.val().replace(/\[(Tab|Enter|Shift|Ctrl|Alt|Break|Caps Lock|Esc|Space|Page (Up|Down)|End|Home|Left|Up|Right|Down|Insert|Delete)\]$/,' '));
$("#txt2").val(el.val());
}
});