Javascript - 像 Google 文档一样检测中文字符输入
我试图可靠地检测何时将中文字符插入到文本框中。如果我将 keyup、keydown 和 keypress 处理程序添加到输入字段,则当用户从 IME(输入法编辑器)中选择中文字符时,不会触发任何事件。例如,在使用简体中文拼音的 Mac/Firefox 上,如果我输入:
ni 然后按 1,
我只会收到“n”的 keydown 事件和“1”的 key up 事件。不会触发任何按键事件。注意:我正在使用 GWT,但我认为这并不重要。
我很好奇 Google 文档是如何做到这一点的。我特别注意到对于中文,“n”字符作为文本附加到具有“docs-texteventtarget-iframe”类的隐藏 iframe(但不是“i”)。我想他们这样做是为了检测何时插入汉字。
Google 文档如何知道输入语言更改为中文?例如,如果我的输入语言是英语并且我输入“n”,则它不会附加到该隐藏的 iframe 中。有没有什么通用的技术来检测汉字按键事件?
I'm trying to reliably detect when chinese characters are inserted into a text box. If I add keyup, keydown, and keypress handlers to an input field, no event is fired when the user selects a chinese character from an IME (input method editor). For example, on Mac/Firefox with Chinese simplified pinyan if I type:
ni then hit 1
I only receive the keydown event for 'n' and the key up for '1'. No keypress event is fired. Note: I'm using GWT but I don't think it should matter.
I was curious how Google docs does this. I noticed specifically for Chinese, the 'n' character appended as text to a hidden iframe with the class "docs-texteventtarget-iframe" (but not the 'i'). I would imagine they're doing this to detect when a chinese character is inserted.
How does Google docs know that the input language changed to chinese? For instance, if my input language is English and I type 'n', it is not appended to that hidden iframe. Is there any common techniques to detecting chinese character key events?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
当用户使用 IME(输入法编辑器)输入文本时,在输入字段的内容发生更改之前,IME 组合窗口内会发生大量交互。您可以通过
compositionstart
和compositionend
事件检测到这一点。事实上,当组合正在进行时,您绝对不想从 IME 窃取 keyup/keydows 事件。在文本输入元素上,您可以通过input
事件捕获内容的变化。When the user inputs text using an IME (Input Method Editor), then before the content of the input field changes, there is a lot of interaction going on within the IME composition window. You can detect this through the
compositionstart
andcompositionend
events. In fact, while composition is in progress, you definitely do not want to steal the keyup/keydows events from the IME. On a text input element you can then catch when the content changes through theinput
event.我怀疑您没有收到按键事件,因为输入来自 IME 而不是键盘,就像粘贴到字段中时您不会收到按键事件一样。
您可以尝试添加 ValueChangeHandler 到文本框以查看是否捕获您正在查找的事件。
I would suspect that you are not getting a keypress event because the input is coming from an IME instead of the keyboard, just as you don't get key events if you paste into a field.
You can try adding a ValueChangeHandler to the textbox to see if that catches the events that you are looking for.