Javascript IFrame / designmode和onkeydown事件问题

时间:2010-09-16 21:19:46

标签: javascript

如果已经回答,请道歉。通过一些相关的问题和谷歌,但最终没有看到为什么这不起作用。

我的代码如下

<iframe id="editor"></iframe>

editorWindow = document.getElementById('editor').contentWindow;
isCtrlDown = false;

function loadEditor()
{
    editorWindow.document.designMode = "on";
    editorWindow.document.onkeyup = function(e) {
        if (e.which == 91) isCtrlDown = false;
    }
    editorWindow.document.onkeydown = handleKeyDown;
}

function handleKeyDown(e)
{
    if (e.which == 91) isCtrlDown = true;
    if (e.which == 66 && isCtrlDown) editFont('bold');
    if (e.which == 73 && isCtrlDown) editFont('italic');
}

function editFont(a,b)
{
    editorWindow.document.execCommand(a,false,b);
    editorWindow.focus();
}

此代码在Chrome中运行良好,但键盘快捷键在Firefox中不起作用。实际上,在Firefox中,似乎根本没有为keyup / keydown注册事件。

我在这里做了一件非常错误的事情,这会让Firefox崩溃吗?

2 个答案:

答案 0 :(得分:2)

对于可编辑文档,您需要使用addEventListener来附加键事件而不是DOM0事件处理程序属性:

editorWindow.document.addEventListener("keydown", handleKeyDown, false);

如果您关心IE 6-8,则需要测试是否存在addEventListener并添加attachEvent等效项(如果缺少)。

答案 1 :(得分:1)

尝试使用:

editorWindow = document.getElementById('editor').frameElement;

我不确定这会解决问题,也可能是:

editorWindow = document.getElementById('editor').contentDocument;

甚至可能:

editorWindow = document.getElementById('editor').frameElement.contentDocument;

您可以做的一件事是将整个字符串放在try语句中以捕获任何错误,并查看是否从iframe中抓取内容。

try { editorWindow = document.getElementById('editor').contentWindow; } catch(e) { alert(e) };

我唯一想到的是你在iframe中输入一个文本框,你可能需要将onkeydown事件添加到该特定项目中,例如:

var editorWindow = document.getElementById('editor').contentDocument;
var textbox = editorWindow.getElementById('my_textbox');

function loadEditor()
{
editorWindow.document.designMode = "on";
textbox.onkeydown = function(e) {
    alert('hello there');
}
}

我希望其中一个是解决方案。我经常发现,当谈到跨平台功能时,它往往归结为一些试验和错误。

祝你好运!

相关问题