简体   繁体   中英

How can i capture Shift + F8 in JQuery application?

I am trying to capture Shift+F8 in my JQuery application & want it to propagate down. I have read many posts but somehow I am not able to catch Shift+F8 key at all. I found 1 useful lib here but it is able to find ' Shift+F2/F3/... ' but not ' Shift+F8 ' particularly. any suggestions please & thanks in advance.

Environment : Windows & IE (11 & 8)

On any modern browser, you can use a keydown or keyup event handler like this one:

document.addEventListener("keydown", function(e) {
    if (e.key === "F8" && e.shiftKey) {
        e.preventDefault();
        // ...Shift+F8 was pressed...
    }
});

or with jQuery:

$(document).on("keydown", function(e) {
    if (e.key === "F8" && e.shiftKey) {
        e.preventDefault();
        // ...Shift+F8 was pressed...
    }
});

Whether that works may be browser-specific, because different browsers reserve different key combinations. It works on Chrome and Firefox on my copy of Linux, and on Edge on Windows 10, and IE11 on Windows 8. Note that you have to click inside the window to ensure it has focus.

You've tagged . If you really need to support that truly obsolete browser, which doesn't have addEventListener , use a version of jQuery that still supports IE8 (or the hookEvent function from this answer , which works on IE8 [or even IE6]) and then instead of using e.key , use e.which || e.keyCode e.which || e.keyCode and the appropriate keycode. The reason we have e.key now is that "the appropriate keycode" varies by keyboard layout. On my keyboard, F8 is 119 , so:

// For obsolete browsers without `addEventListener`
hookEvent(document, "keydown", function(e) {
    if ((e.which || e.keyCode) === 119 && e.shiftKey) {
        e.preventDefault();
        // ...Shift+F8 was pressed...
    }
});

or using an older version of jQuery that supports IE8:

// For obsolete browsers
$(document).on("keydown", function(e) {
//               ^---- if it's a REALLY old version, you might need `bind` instead of `on`
    if ((e.which || e.keyCode) === 119 && e.shiftKey) {
        e.preventDefault();
        // ...Shift+F8 was pressed...
    }
});
document.onkeydown = function(evt){
    evt = evt || window.event;
    if(evt.shiftKey && evt.key == "F8"){

    }
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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