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

元气小坏坏 提交于 2019-12-11 05:51:16

问题


As you know, most of rich text editor use iframe to create WYSIWYG editor. In iframe contain document that is in design mode. I want to capture key down event when user press '@' character in rich text editor for displaying autocomplete for it.

By the way, i cannot see any fired event inside design mode. How can I solve this question?


回答1:


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.

To capture the user typing the '@' character (or indeed any printable character), you should use the keypress event rather than 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;
}


来源:https://stackoverflow.com/questions/1778393/is-possible-to-capture-keydown-event-when-current-document-is-in-design-mode

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!