Handling key-press events (F1-F12) using JavaScrip

2019-01-03 13:53发布

I want to handle F1-F12 keys using JavaScript and jQuery.

I am not sure what pitfalls there are to avoid, and I am not currently able to test implementations in any other browsers than Internet Explorer 8, Google Chrome and Mozilla FireFox 3.

Any suggestions to a full cross-browser solution? Something like a well-tested jQuery library or maybe just vanilla jQuery/JavaScript?

13条回答
Viruses.
2楼-- · 2019-01-03 14:21

This works for me.

if(code ==112) { alert("F1 was pressed!!"); return false; }

F2 - 113, F3 - 114, F4 - 115, and so fort.

查看更多
We Are One
3楼-- · 2019-01-03 14:23

Wow it is very simple. i'm blame to write this, why no one make it before?

$(function(){
    //Yes! use keydown 'cus some keys is fired only in this trigger,
    //such arrows keys
    $("body").keydown(function(e){
         //well you need keep on mind that your browser use some keys 
         //to call some function, so we'll prevent this
         e.preventDefault();

         //now we caught the key code, yabadabadoo!!
         var keyCode = e.keyCode || e.which;

         //your keyCode contains the key code, F1 to F12 
         //is among 112 and 123. Just it.
         console.log(keyCode);       
    });
});
查看更多
仙女界的扛把子
4楼-- · 2019-01-03 14:24

The best source I have for this kind of question is this page: http://www.quirksmode.org/js/keys.html

What they say is that the key codes are odd on Safari, and consistent everywhere else (except that there's no keypress event on IE, but I believe keydown works).

查看更多
Melony?
5楼-- · 2019-01-03 14:24

When you use angular.js for handling events, you should use ng-keydown for preventing pause in developer in chrome.

查看更多
来,给爷笑一个
6楼-- · 2019-01-03 14:27

I agree with William that in general it is a bad idea to hijack the function keys. That said, I found the shortcut library that adds this functionality, as well as other keyboard shortcuts and combination, in a very slick way.

Single keystroke:

shortcut.add("F1", function() {
    alert("F1 pressed");
});

Combination of keystrokes:

shortcut.add("Ctrl+Shift+A", function() {
    alert("Ctrl Shift A pressed");
});
查看更多
▲ chillily
7楼-- · 2019-01-03 14:28

You can do this with jquery like this:

        $("#elemenId").keydown(function (e) {
            if(e.key == "F12"){
                console.log(e.key);
            }

        });
查看更多
登录 后发表回答