How do I give an HTML canvas the keyboard focus using jquery?

前端 未结 2 1748
走了就别回头了
走了就别回头了 2021-01-04 06:20

I am implementing a game using Javascript, jquery, and the Canvas tag. How can I prevent the browser from processing keyboard shortcuts when the canvas tag has the focus? I

相关标签:
2条回答
  • 2021-01-04 06:42

    Try event.preventDefault();. Also there are keypress, keydown, and keyup events... you could try each of them to see which works.

    0 讨论(0)
  • 2021-01-04 07:00

    The root problem is that by default the browser doesn't make the canvas "focusable". The best workaround I could come up with is to set the tabindex on the canvas:

    $("#canvas")
        // Add tab index to ensure the canvas retains focus
        .attr("tabindex", "0")
        // Mouse down override to prevent default browser controls from appearing
        .mousedown(function(){ $(this).focus(); return false; }) 
        .keydown(function(){ /* ... game logic ... */ return false; });
    

    If for whatever reason you can't set the tabindex, you can also make the canvas "focusable" by setting contentEditable to true:

    // Add content editable to help ensure the canvas retains focus
    $("#canvas").attr("contentEditable", "true")
    $("#canvas")[0].contentEditable = true;
    

    This is the solution I came up with originally, but in my opinion it's a bit hackier than the tabindex option.

    Another thing to consider is that browsers tend to outline content editable elements with a border. This can be off-putting to some users. Luckily, you can get rid of it with this bit of css:

    #canvas { outline: none; }
    

    I've tested both solutions in Chrome 3/4/5 and FireFox 3.0/3.5/3.6 on Windows XP, Mac OSX and Linux. Here's a working example: http://xavi.co/static/so-canvas-keyboard.html

    0 讨论(0)
提交回复
热议问题