Javascript IFrame/designmode和onkeydown事件问题
如果已经回答了,请道歉。浏览了一些与谷歌相关的问题,但最终没能理解为什么这不起作用 我的代码如下Javascript IFrame/designmode和onkeydown事件问题,javascript,Javascript,如果已经回答了,请道歉。浏览了一些与谷歌相关的问题,但最终没能理解为什么这不起作用 我的代码如下 <iframe id="editor"></iframe> editorWindow = document.getElementById('editor').contentWindow; isCtrlDown = false; function loadEditor() { editorWindow.document.designMode = "on";
<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();
}
editorWindow=document.getElementById('editor').contentWindow;
isCtrlDown=false;
函数loadEditor()
{
editorWindow.document.designMode=“on”;
editorWindow.document.onkeyup=函数(e){
如果(e.which==91)isCtrlDown=false;
}
editorWindow.document.onkeydown=handleKeyDown;
}
功能handleKeyDown(e)
{
如果(e.which==91)isCtrlDown=true;
如果(e.which==66&&isCtrlDown)编辑字体('bold');
如果(e.which==73&&isCtrlDown)编辑字体('italic');
}
函数编辑字体(a,b)
{
editorWindow.document.execCommand(a,false,b);
editorWindow.focus();
}
这段代码在Chrome中运行得非常好,但在Firefox中键盘快捷键不起作用。事实上,在Firefox中,它似乎根本没有注册keyup/keydown事件
我是不是做错了什么事情,把Firefox搞得一团糟了?试试使用:
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');
}
}
我希望其中之一就是解决办法。我经常发现,当涉及到跨平台功能时,它往往归结为一个小的尝试和错误
祝你好运 对于可编辑文档,您需要使用
addEventListener
来附加关键事件,而不是DOM0事件处理程序属性:
editorWindow.document.addEventListener("keydown", handleKeyDown, false);
如果您关心IE 6-8,则需要测试是否存在
addEventListener
,如果缺少,则添加attachEvent
等效项。谢谢。您可以通过单击答案左侧的绿色勾号来接受答案。不幸的是,您不能接受答案。可能只是Firefox的实现有点奇怪,或者是Chromes的一些特别之处。我最终使用了AddEventListener,就像上面有人建议的那样。谢谢你的帮助。