繁体   English   中英

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

[英]How can I use onkeydown outside of an input element?

我在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

}   

使用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:

var shiftPressed = false;

document.addEventListener ('keydown', function(event) {
  shiftPressed = event.shiftKey;
});

document.addEventListener ('keyup', function(event) {
  shiftPressed = event.shiftKey;
});

然后更改您的功能:

if (shiftPressed) {popit(chn);}

JS小提琴: https : //jsfiddle.net/charlesartbr/6L4juxbk/

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM