我如何给一个HTML画布的键盘焦点使用jquery? [英] How do I give an HTML canvas the keyboard focus using jquery?

查看:118
本文介绍了我如何给一个HTML画布的键盘焦点使用jquery?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用Javascript,jquery和Canvas标签来实现一个游戏。当画布标签具有焦点时,如何防止浏览器处理键盘快捷键?我尝试了event.stopPropagation(),它没有效果。



我可以拿起键盘事件。但是,当用户按下空格键时,网页在Firefox中向下滚动。箭头键也一样。

解决方案

根问题是,默认情况下浏览器不会使画布可聚焦。我能想出的最好的解决方法是在画布上设置 tabindex

  $(#canvas)
//添加制表符索引以确保画布保持焦点
.attr(tabindex,0)
//鼠标向下防止默认浏览器控件出现
.mousedown(function(){$(this).focus(); return false;})
。 ... * / return false;});

如果由于某种原因不能设置 tabindex ,您还可以通过将 contentEditable 设置为true来使画布可聚焦:

  //添加内容可编辑以帮助确保画布保持焦点
$(#canvas)。attr(contentEditable,true)
$ )[0] .contentEditable = true;

这是我原来提出的解决方案,但在我看来, code> tabindex 选项。



另一件需要考虑的事情是浏览器倾向于使用边框勾勒内容可编辑元素。这可能是对一些用户的。幸运的是,你可以用这个位css删除它:

  #canvas {outline:none; }我已经在Chrome 3/4/5和FireFox 3.0 / 3.5 / 3.6中测试了这两个解决方案在Windows XP,Mac OSX和Linux上。以下是一个工作示例: http://xavi.co/static/so-canvas-keyboard .html  


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 have tried event.stopPropagation() and it has no effect.

I can pick up keyboard events. However, when the user presses the spacebar, the web page scrolls down in Firefox. The same happens with the arrow keys.

解决方案

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

这篇关于我如何给一个HTML画布的键盘焦点使用jquery?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆