我在JS画布上有点。我点击它们来启动不同的功能。我已经在使用鼠标右键和左键单击了,但是如果我在左键单击时按下了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
}
发布于 2019-05-07 18:37:03
使用vanilla javascript:
var shiftPressed = false;
document.addEventListener ('keydown', function(event) {
shiftPressed = event.shiftKey;
});
document.addEventListener ('keyup', function(event) {
shiftPressed = event.shiftKey;
});
然后更改您的函数:
if (shiftPressed) {popit(chn);}
发布于 2019-05-07 18:36:21
使用window.addEventListener("keydown/keyup", ...)
将keydown
和keyup
事件附加到window
,并保留一个跟踪按下shift键状态的全局变量。
然后在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
}
}
https://stackoverflow.com/questions/56028484
复制