如何使用jquery为HTML画布提供键盘焦点? [英] How do I give an HTML canvas the keyboard focus using jquery?

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

问题描述

我正在使用Javascript,jquery和Canvas标签来实现游戏。当canvas标签有焦点时,如何防止浏览器处理键盘快捷键?我已经尝试过event.stopPropagation(),它没有任何效果。



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

解决方案

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

  $(#canvas)
//添加选项卡索引以确保画布保留焦点
.attr(tabindex,0)
//鼠标下拉覆盖以防止默认浏览器控件出现
.mousedown(function(){$(this).focus(); return false;})
.keydown(function(){/ * ...游戏逻辑... * / return false;});

如果由于任何原因您无法设置 tabindex ,您还可以通过将 contentEditable 设置为true来使画布focusable:

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

这是我最初提出的解决方案,但在我看来,它比 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

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

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