addEventListener用于Canvas上的键下拉 [英] addEventListener for keydown on Canvas

查看:177
本文介绍了addEventListener用于Canvas上的键下拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个响应键盘和鼠标输入的画布应用程序。我有这个代码:

  canvas = document.getElementById('canvas'); 
canvas.addEventListener('mousedown',function(event){
alert('mousedown');
},false);
canvas.addEventListener('keydown',function(event){
alert('keydown');
},false);

当我点击鼠标时出现mousedown向上。相同的代码在JS Bin上正常工作: http://jsbin.com/uteha3/66/



为什么在我的网页上无法使用?

>一个解决方案,但一个更简单和正确的方法是在canvas元素上设置 tabindex 属性(由hobberwickey建议)。



您不能关注画布元素。

  var lastDownTarget,canvas;这是一个简单的工作, 
window.onload = function(){
canvas = document.getElementById(`canvas');

document.addEventListener('mousedown',function(event){
lastDownTarget = event.target;
alert('mousedown');
},false) ;

document.addEventListener('keydown',function(event){
if(lastDownTarget == canvas){
alert('keydown');
}
},false);
}

JSFIDDLE


I am trying to make a canvas app that responds to keyboard and mouse input. I have this code:

canvas = document.getElementById('canvas');
canvas.addEventListener('mousedown', function(event) {
    alert('mousedown');
        }, false);
canvas.addEventListener('keydown', function(event) {
    alert('keydown');
        }, false);

The 'mousedown' alert comes up whenever I click the mouse, but the 'keydown' alert never comes up. The same code works fine on JS Bin: http://jsbin.com/uteha3/66/

Why isn't it working on my page? Does canvas not recognize keyboard input?

解决方案

Edit - This answer is a solution, but a much simpler and proper approach would be setting the tabindex attribute on the canvas element (as suggested by hobberwickey).

You can't focus a canvas element. A simple work around this, would be to make your "own" focus.

var lastDownTarget, canvas;
window.onload = function() {
    canvas = document.getElementById('canvas');

    document.addEventListener('mousedown', function(event) {
        lastDownTarget = event.target;
        alert('mousedown');
    }, false);

    document.addEventListener('keydown', function(event) {
        if(lastDownTarget == canvas) {
            alert('keydown');
        }
    }, false);
}

JSFIDDLE

这篇关于addEventListener用于Canvas上的键下拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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