Blocking default action on keypress with iframe

瘦欲@ 提交于 2019-12-04 15:00:52

I may not fully understand the problem, but it seems like you want:

  1. up, down, space, etc. to go only to the game window only when that has focus.
  2. up, down, space, etc. to go to the comment box when that has focus.
  3. up, down, space, etc. to go to the main window when that has focus.

Number #2 and #3 are what happen automatically if you do nothing. So basically you want #1. I don't see why you need any code on the main window.

This works in Chrome, Opera, FF, IE9, IE8, IE7 in my tests.

Main Window

Demo: http://jsfiddle.net/ThinkingStiff/Dp5vK/

HTML:

<iframe id="game" src="http://jsfiddle.net/ThinkingStiff/dtmxy/show/"></iframe>
<textarea id="comment-box"></textarea>

CSS:

#game {
    border: 1px solid red;
    display: block;
    height: 100px;
    width: 200px;
}

#comment-box {
    height: 100px;
    width: 200px;
}

body {
    height: 1000px;
    width: 1000px;
}

Game Window (iframe)

Demo: http://jsfiddle.net/ThinkingStiff/dtmxy/

Script:

$( document ).bind( 'keydown', function ( event ) {

    var keys = [32, 33, 34, 35, 36, 37, 38, 39, 40, 44];

    if( keys.indexOf( event.which ) > -1 ) {

        event.preventDefault();
        event.stopPropagation();

    };

} );

See if it helps when you change it to only catch on the game div.

$('div.arcade-content').on('keydown', 'div.game-wrapper', function (e) {
    ...
});

Concerning the space bar issue you have to check in your keydown function if the user just focused the comment box below the game. If it is focused, then allow spacebar temporarily.

Give your game canvas a tabindex. A value of 0 will put the canvas element in the regular source-based tab order. It will then be able to receive focus and act as the target of key events, meaning you can prevent default actions and event propagation for key events originating from your canavas only.

$canvas = $("#c2canvas");
$canvas.tabIndex = 0;

var ar = [32, 33, 34, 35, 36, 37, 38, 39, 40, 44];
$canvas.keydown(function (e) {            
    var key = e.which;
    if ($.inArray(key, ar) > -1) {
        e.preventDefault();
        e.stopPropagation();
    }
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!