简体   繁体   English

当前文档处于设计模式时,是否可以捕获KeyDown事件?

[英]Is possible to capture KeyDown event when current document is in design mode?

As you know, most of rich text editor use iframe to create WYSIWYG editor. 如您所知,大多数RTF编辑器都使用iframe创建所见即所得编辑器。 In iframe contain document that is in design mode. 在iframe中包含处于设计模式的文档。 I want to capture key down event when user press '@' character in rich text editor for displaying autocomplete for it. 我想捕获当用户在RTF编辑器中按'@'字符以显示其自动完成功能时按下按键的事件。

By the way, i cannot see any fired event inside design mode. 顺便说一句,我在设计模式下看不到任何触发的事件。 How can I solve this question? 我该如何解决这个问题?

It's perfectly possible to capture all key events in documents with designMode turned on, though you have to use addEventListener on document in Firefox (and possibly others) rather than assigning your handler to document.onkeypress . 尽管必须在Firefox(可能还有其他)中的document上使用addEventListener ,而不是将处理程序分配给document.onkeypress ,但是完全可以在designMode的情况下捕获文档中的所有关键事件。

To capture the user typing the '@' character (or indeed any printable character), you should use the keypress event rather than keydown . 要捕获键入'@'字符(或实际上是任何可打印字符)的用户,您应该使用keypress事件而不是keydown

// Assuming you have a reference to your iframe in a variable called 'iframe':

function handleIframeKeyPress(evt) {
    evt = evt || iframe.contentWindow.event;
    var charCode = evt.keyCode || evt.which;
    var charTyped = String.fromCharCode(charCode);
    if (charTyped === "@") {
        alert("@ typed");
    }
}

var doc = iframe.contentWindow.document;

if (doc.addEventListener) {
    doc.addEventListener("keypress", handleIframeKeyPress, false);
} else if (doc.attachEvent) {
    doc.attachEvent("onkeypress", handleIframeKeyPress);
} else {
    doc.onkeypress = handleIframeKeyPress;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM