Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.3k views
in Technique[技术] by (71.8m points)

jquery - Overriding the F1 key in FF, chrome, ie. Is F1 on ie8/chrome on keyup and in FF on keypress? What about <tab> in an input field?

I'm creating namespaced events with jquery. When I use the following function with code=112, a function, bool=false, everything works fine in FF and the F1 key submits to my function and the event does not bubble up to open the firefox help in a new tab.

function bindKeyFunc(code, func, bool){
    $(document).bind('keypress.' + code, function(e){
        var c = (e.keyCode ? e.keyCode : e.which);
        //console.log(c);
        if ( code == c) {
            //e.stopPropagation();
            //e.preventDefault();
            func();
            return bool;
        }
    });
}

In chrome and ie8 my event listener does not fire and the regular help occurs instead, even if I uncomment the stopPropagation and preventDefault calls.

Similarly, when I try to take over the <tab> key for my own purposes, it works splendidly in FF but my event doesn't fire in chrome or ie8 and the default action for the tab fires instead:

    $('input#manual-total').bind('keypress.dep', function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if ( code==9 ){
            $('div#formset').show();
            $(next).focus()[0].select();
            return false;
        }
    });
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

A plain document.addEventListener on keydown worked for me on Chrome.

var util = { };

document.addEventListener('keydown', function(e){

    var key = util.key[e.which];
    if( key ){
        e.preventDefault();
    }

    if( key === 'F1' ){        
      // do stuff
    }
})

util.key = { 
  9: "tab",
  13: "enter",
  16: "shift",
  18: "alt",
  27: "esc",
  33: "rePag",
  34: "avPag",
  35: "end",
  36: "home",
  37: "left",
  38: "up",
  39: "right",
  40: "down",
  112: "F1",
  113: "F2",
  114: "F3",
  115: "F4",
  116: "F5",
  117: "F6",
  118: "F7",
  119: "F8",
  120: "F9",
  121: "F10",
  122: "F11",
  123: "F12"
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...