我一直在这个论坛寻找解决方案,但尚未找到。无论我在页面上的哪个位置单击,我都需要始终将焦点放在画布元素上。我有几个按钮,在每个 onclick 事件中我写:
document.getElementById('canvas').focus();
这确实有效,但我认为这不是最好的做法。任何想法?
默认情况下,画布元素不可聚焦。你需要设置一个tabIndex
首先。
Example
document.querySelector("canvas").onblur = function() {
var me = this;
me.style.background = "red";
setTimeout(function() {
me.style.background = "transparent";
me.focus();
}, 500);
}
canvas {border:1px solid #000}
Click on canvas then outside - a blur event will be thrown coloring the background red for half a second:<br>
<canvas tabindex=0 ></canvas>
但是,我真的看不出您需要强制关注画布元素的任何原因。
如果您想捕获鼠标和按键事件,有更好的方法可以做到这一点,例如防止事件冒泡。强制焦点还会阻止输入字段的工作、可访问性等。
这是捕获鼠标移动和按键事件并将它们重定向到画布使用的一种方法:
“劫持”事件示例
var ctx = document.querySelector("canvas").getContext("2d");
// redirect events
window.addEventListener("mousemove", function(e) {
var rect = ctx.canvas.getBoundingClientRect(),
x = e.clientX - rect.left,
y = e.clientY - rect.top;
ctx.fillRect(x-2, y-2, 4, 4);
});
window.addEventListener("keydown", function(e) {
e.preventDefault();
ctx.fillText(e.keyCode, Math.random() * 300, Math.random() * 150);
});
html, body {width:100%;height:100%;margin:0;overflow:hidden}
canvas {border:1px solid #000}
<h1>Demo</h1>
<p>Active this window by clicking in it, then hit some keys and move mouse around</p>
<canvas tabindex=0></canvas>
<h2>End</h2>
<button>Test button</button>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)