Is there a way to detect which side the Alt key was pressed on (right or left)?

前端 未结 3 549
傲寒
傲寒 2020-12-01 14:25

Is there a way that we can detect which side the Alt key was pressed on, i.e. distinguish between left or right Alt? I saw somewhere that it\'s possibl

3条回答
  •  抹茶落季
    2020-12-01 14:54

    Good question. The event object does not contain anything about which alt is pressed but you can try something like this:

    var altLeft = false,
        altRight = false,
        time = null;
    
    document.onkeydown = function (e) {
        e = e || window.event;
        //The time check is because firefox triggers alt Right + alt Left when you press alt Right so you must skip alt Left if it comes immediatelly after alt Right
        if (e.keyCode === 18 && (time === null || ((+new Date) - time) > 50)) {
            altLeft = true;
            time = null;
        } else if (e.keyCode === 17) {
            altRight = true;
            time = + new Date;
        }
    }
    
    document.onkeyup = function (e) {
        e = e || window.event;
        if (e.keyCode === 18) altLeft = false;
        else if (e.keyCode === 17) altRight = false;
    }
    
    document.onclick = function () {
        console.log("left", altLeft, "right", altRight);
    }
    

    It works for me in Firefox, anyway the 17 and 18 (that are key codes for alt Right and Left) can change on different browsers or operating systems so you must check them.

提交回复
热议问题