当当前文档处于设计模式时可以捕获KeyDown事件吗? [英] Is possible to capture KeyDown event when current document is in design mode?

查看:143
本文介绍了当当前文档处于设计模式时可以捕获KeyDown事件吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如您所知,大多数富文本编辑器使用iframe创建所见即所得编辑器。在iframe中包含处于设计模式的文档。当用户在富文本编辑器中按'@'字符显示自动填充时,我想捕获关键事件。



顺便说一下,我看不到任何触发的事件设计模式。如何解决这个问题?

解决方案

完全可以使用 designMode捕获文档中的所有关键事件打开,虽然您必须在Firefox(或许其他的)中使用文档上的 addEventListener )而不是将你的处理程序分配给 document.onkeypress



要捕获输入'@'字符的用户或者确实是任何可打印字符),您应该使用 keypress 事件而不是 keydown

  //假设你有一个名为'iframe'的变量的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;
}


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?

解决方案

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;
}

这篇关于当当前文档处于设计模式时可以捕获KeyDown事件吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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