我在 JS Canvas 上有点。我点击它们来启动不同的功能。 我已经在使用右键单击和左键单击,但如果我在左键单击时按下 SHIFT,我想做一些不同的事情。
我需要检测 onkeydown,但光标不在输入元素中。 我怎样才能做到这一点?
例如:
function getPosition3(event) // to get click position in canvas3
{ var canvas = document.getElementById("canvas3");
mousePos = getMousePos(canvas, event);
ge3.px = mousePos.x;
ge3.py = mousePos.y;
p2g(ge3); // converts pixels to graphic coordinates ge3.gx & ge3.gy
closestDist = 5000000;
chn = -1; // will contain index of the closest hedge to the click
[nearestX, nearestY, chn] = nearestHedge(ge3.gx, ge3.gy);
rnddot(ge3, nearestX, nearestY, 4, '#000000', 0);
if (event.which==3) {popit(chn);} //popup graph on right click
else {poptxt(chn);}
// Here I'd like to detect onkeydown to allow another option
}
最佳答案
使用 window.addEventListener("keydown/keyup", ... 将
并保留一个全局变量来跟踪 Shift 键按下状态。keydown
和 keyup
事件附加到 window
)
然后在 getPosition3
函数中检查该变量。
var shiftPressed = false;
window.addEventListener("keydown", function(ev) {
shiftPressed = ev.shiftKey; // or whatever property. Just written on-the-fly and I'm not sure if is shiftKey.
});
window.addEventListener("keyup", function(ev) {
shiftPressed = ev.shiftKey;
});
function getPosition3(event) {
// [...]
// blah blah
// [...]
if (shiftPressed) {
// Things
}
}
关于javascript - 如何在输入元素之外使用 onkeydown?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56028484/