开发者

Javascript IFrame/designmode and onkeydown event question

开发者 https://www.devze.com 2023-01-16 06:25 出处:网络
Apologize if this is answered already.Went through some of the related questions and google, but ultimately failed to see why this isn\'t working.

Apologize if this is answered already. Went through some of the related questions and google, but ultimately failed to see why this isn't working.

My code is as follows

<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 && isC开发者_如何学GotrlDown) editFont('italic');
}

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

This code works perfectly in Chrome, but the keyboard shortcuts do not work in Firefox. In fact, in Firefox it does not seem to register the events for keyup/keydown at all.

Am I doing something grossly wrong here that is mucking up Firefox?


For editable documents, you need to use addEventListener to attach key events rather than DOM0 event handler properties:

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

If you care about IE 6-8, you will need to test for the existence addEventListener and add the attachEvent equivalent if it is missing.


Try using:

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

I'm not sure this will solve the issue, it may also be:

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

Or even possibly:

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

One thing you can do is put the entire string in a try statement to catch any errors and see if the content is being grabbed from within the iframe.

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

The only other thought I have is that you're typing into a textbox which is within an iframe, and you may possibly have to add the onkeydown event to that specific item, such as:

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

I hope one of these is the solution. I often find when it comes to cross-platform functionality it often boils down to a little trial and error.

Good Luck!

0

精彩评论

暂无评论...
验证码 换一张
取 消