addEventListener for keydown on Canvas(addEventListener 用于 Canvas 上的 keydown)
问题描述
我正在尝试制作一个响应键盘和鼠标输入的画布应用程序.我有这个代码:
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);
每当我单击鼠标时都会出现mousedown"警报,但从未出现过keydown"警报.相同的代码在 JS Bin 上运行良好:http://jsbin.com/uteha3/66/
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?
推荐答案
编辑 - 这个答案是一个解决方案,但更简单和正确的方法是设置画布元素上的 tabindex 属性(由 hobberwickey 建议).
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).
您无法聚焦画布元素.解决这个问题的一个简单方法是让你自己"关注.
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 上的 keydown的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:addEventListener 用于 Canvas 上的 keydown
				
        
 
            
        基础教程推荐
- jQuery File Upload - 如何识别所有文件何时上传 2022-01-01
 - 为什么我在 Vue.js 中得到 ERR_CONNECTION_TIMED_OUT? 2022-01-01
 - 如何使用 CSS 显示和隐藏 div? 2022-01-01
 - 什么是不使用 jQuery 的经验技术原因? 2022-01-01
 - WatchKit 支持 html 吗?有没有像 UIWebview 这样的控制器? 2022-01-01
 - 如何在特定日期之前获取消息? 2022-01-01
 - 每次设置弹出窗口的焦点 2022-01-01
 - Javascript 在多个元素上单击事件侦听器并获取目标 2022-01-01
 - 如何使用sencha Touch2在单页中显示列表和其他标签 2022-01-01
 - Node.js 有没有好的索引/搜索引擎? 2022-01-01
 
    	
    	
    	
    	
    	
    	
    	
    	
						
						
						
						
						
				
				
				
				