当按下不可打印的字符时,它会被替换为 CTRL=17 的“[CTRL]”。 这是代码示例
$('#textbox1').keyup(function (event) {
if (8 != event.keyCode) {
if(17==event.keyCode){
$('#textbox1').val($('#textbox1').val()+"[CTRL]")
$('#textbox2').val($('#textbox1').val());
}else{
$('#textbox2').val($('#textbox1').val());
}
} else {
$('#textbox2').val($('#textbox1').val());
}
});
问题是当用户按退格键时,第二个输入必须反射(reflect)第一个输入的内容,因此必须像任何其他字符一样立即删除“[CTRL]”。
最佳答案
您可以使用keyCode
和/或与charCode
结合使用(如果需要)。基本想法是:
- 在数组/对象中创建所有必需键代码的映射
- 处理
keydown
事件并监听键码 - 在 map 中查找键码,如果找到则显示
- 防止默认(防止例如退格浏览)
- 如果在 map 中找不到,则让 Angular 色照常穿过。
一个非常基本的例子:
演示: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
});
关于删除描述,我无法通过缓存 map 中最后插入的描述来完成。不知何故,我一直在与带有变量的正则表达式作斗争。无论如何,一个更简单的解决方案是使用硬编码映射添加另一个用于 keyup 的事件处理程序。
感谢@serakfalcon (that simple solution) ,我们在这里使用:
$('#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());
}
});
关于javascript - 使用不可打印的字符(例如 CTRL、ALT 或 Shift 键)镜像输入内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23502392/