简体   繁体   中英

JavaScript keyDown Does Not Fire

I have a page in a modal window where I am displaying a slide show. The intended audience is for tablet users and they navigate the show by swiping from the right to the left or the left to the right to see the next or previous slide. This all works beautifully.

However, in the event that someone does view the page using a computer, I would like them to be able to navigate using the arrow keys on their keyboard. I'm able to detect the keystroke, but only after the user has clicked inside the modal window. I would really like the user to not have to click anywhere before the keyboard navigation shows up. It doesn't seem to matter what I try, this is always the problem.

Please note, because this is a modal window, it brings its contents in through the use of an iFrame.

Here is the code. I have confirmed that it does run when the page loads, and the pageTurn function works with other events:

document.onkeydown = function(e){   
    if (e == null) {
        keycode = event.keyCode;
    } else {
        keycode = e.which;
    }
    if(keycode == 37){
        pageTurn('right');
    } else if(keycode == 39){
        pageTurn('left');
    }   
};

Try attaching the event to document.documentElement instead of just document .

If this fails, try adding document.body.focus() to ensure the document is ready to receive keyboard input.

EDIT: Inside an iFrame, the event needs to be attached to the top.document.documentElement instead, or attached to all frames as explained here

document is fine for attaching key events. Also, keyCode is the correct property in all major browsers for keydown and keyup events, so there's no need to mess around with which .

For attaching to the parent document from within an iframe, as one of your comments suggests, you need to use parent (for the immediate parent document's window) or top (the outermost document's window):

parent.document.onkeydown = function(e) {
    e = e || parent.event;
    var keyCode = e.keyCode;
    if (keyCode == 37) {
        pageTurn('right');
    } else if (keyCode == 39) {
        pageTurn('left');
    }
};

Maybe your key codes are wrong. Here is a page which shows you the codes for your browser: http://asquare.net/javascript/tests/KeyCode.html

If the codes are correct, compare the event handling code on this page with your version.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM