改变按键 [英] Changing the keypress

查看:130
本文介绍了改变按键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在输入框或contenteditable = true div中,如何修改字母a的按键以返回字母b的按键?也就是说,每当你在div中输入一个字母a,输出实际上就是字母b。

In an input box or contenteditable=true div, how can I modify a keypress for the letter "a" to return a keybress for the letter "b"? I.e., every time you type the letter "a" in the div, the output is actually the letter "b".

我不是关心一个解决方案在IE中工作 - 只有一个适用于Safari,Chrome和& FF。

I'm not that concerned with a solution that works in IE--just one that works in Safari, Chrome, & FF.

在Chrome中,我可以看到按键事件具有属性charCode,keyCode和哪个,所有这些都被分配了按键事件编号。如果我在按键上触发一个事件,我可以修改这些值,但是我无法弄清楚要返回的内容,以便键入的实际键不同。例如:

In Chrome, I can see that a keypress event has the properties "charCode", "keyCode", and "which", all of which get assigned the keypress event number. If I fire an event on a keypress, I can modify these values, but I can't figure out what to return so that the actual key that gets typed is different. For example:

$(window).keypress(function(e){  //$(window) is a jQuery object
    e.charCode = 102;
    e.which = 102;
    e.keyCode = 102;
    console.log(e);
    return e;
});

我还可以看到,随着charCode,和keyCode,还有一个originalEvent属性又具有这些属性。但是,我没有能够修改这些(我尝试过像e.originalEvent.charCode = 102这样的东西)。

I can also see that along with charCode, which, and keyCode, there is also an "originalEvent" property which in turn also has these properties. However, I haven't been able to modify those (I tried with things like e.originalEvent.charCode = 102).

推荐答案

您不能更改与键事件关联的字符或键,或完全模拟键事件。但是,您可以自己处理按键,并在当前插入点/插入符处手动插入所需的字符。我已经提供了代码来在堆栈溢出的许多地方这样做。对于 contenteditable 元素:

You can't change the character or key associated with a key event, or fully simulate a key event. However, you can handle the keypress yourself and manually insert the character you want at the current insertion point/caret. I've provided code to do this in a number of places on Stack Overflow. For a contenteditable element:

  • Need to set cursor position to the end of a contentEditable div, issue with selection and range objects

这是一个jsFiddle示例: http://www.jsfiddle.net/Ukkmu/4/

Here's a jsFiddle example: http://www.jsfiddle.net/Ukkmu/4/

对于输入:

显示不同的键盘字符在Google Chrome中

跨浏览器jsFiddle示例: http://www.jsfiddle.net/EXH2k/6/

Cross-browser jsFiddle example: http://www.jsfiddle.net/EXH2k/6/

IE> = 9和非IE jsFiddle示例: http://www.jsfiddle.net/EXH2k/ 7 /

IE >= 9 and non-IE jsFiddle example: http://www.jsfiddle.net/EXH2k/7/

这篇关于改变按键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆