javascript - 如何在输入元素之外使用 onkeydown?

标签 javascript onkeydown

我在 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", ... 将 keydownkeyup 事件附加到 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
    }
}

关于javascript - 如何在输入元素之外使用 onkeydown?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56028484/

相关文章:

javascript - 有没有不使用 scroll() 或 scrollTo() 就可以设置窗口滚动位置的方法?

按住多个键时不会触发 JavaScript KeyDown 事件

javascript - 使用 jquery conextmenu 的参数调用函数

javascript - 使用 React useState 钩子(Hook)向循环内的对象添加键值对

Javascript onkeydown 函数运行然后显示消失

javascript - 通过 JavaScript 使用数值从下拉框中选择项目

c# - 从自动完成建议列表中选择一个项目会引发带有 ENTER 键的 KeyDown 事件

javascript - 如何从 Enzyme 获取 React children

javascript - javascript中如何完全执行一个函数而不跳转到另一个函数

javascript - 范围内的 Switch 语句不起作用