Pergunta

Eu quero lidar com F1-F12 keys usando JavaScript e jQuery.

Eu não tenho certeza de que obstáculos existem para evitar, e não estou capaz de testar implementações em qualquer outro navegador que não o Internet Explorer 8, Google Chrome e Mozilla FireFox 3.

Qualquer sugestão para um total de cross-browser solução?Algo como um bem-testado biblioteca jQuery ou talvez apenas de baunilha jQuery/JavaScript?

Foi útil?

Solução

A melhor fonte que eu tenho por esse tipo de pergunta é esta página: http: // www. quirksmode.org/js/keys.html

O que eles dizem é que os códigos de teclas são ímpares no Safari, e consistente em toda a parte (exceto que não há nenhum evento de teclado no IE, mas acredito obras keydown).

Outras dicas

Concordo com William que, em geral, é uma má idéia de seqüestrar as teclas de função. Dito isto, eu encontrei o href="http://www.openjs.com/scripts/events/keyboard_shortcuts/" rel="noreferrer"> atalho biblioteca que adiciona essa funcionalidade, bem como outro teclado atalhos e combinação, de uma forma muito liso.

única tecla:

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

A combinação de teclas:

shortcut.add("Ctrl+Shift+A", function() {
    alert("Ctrl Shift A pressed");
});

Não tenho a certeza se interceptar teclas de função é possível, mas eu gostaria de evitar o uso de teclas de função todos juntos. As teclas de função são usados ??por navegadores para executar uma variedade de tarefas, alguns deles bastante comum. Por exemplo, no Firefox no Linux, pelo menos seis ou sete das teclas de função são reservados para uso pelo navegador:

  • F1 (Ajuda),
  • F3 (Search),
  • F5 (Atualizar),
  • F6 (foco barra de endereços),
  • F7 (modo de navegação acento circunflexo),
  • F11 (modo de tela cheia), e
  • F12 (utilizado por vários add-ons, incluindo Firebug)

A pior parte é que diferentes navegadores em diferentes sistemas operacionais usam chaves diferentes para coisas diferentes. Isso é um monte de diferenças para explicar. Você deve ficar para mais seguro, menos comumente usado combinações de teclas.

Sem outra classe externa você pode criar o seu código de corte pessoal simplesmente usando

event.keyCode

Outra ajuda para todos, eu acho que é esta página de teste para interceptar a keyCode (simplesmente copiar e colar no novo file.html para testar seu evento).

 <html>
 <head>
 <title>Untitled</title>
 <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
 <style type="text/css">
 td,th{border:2px solid #aaa;}
 </style>
 <script type="text/javascript">
 var t_cel,tc_ln;
 if(document.addEventListener){ //code for Moz
   document.addEventListener("keydown",keyCapt,false); 
   document.addEventListener("keyup",keyCapt,false);
   document.addEventListener("keypress",keyCapt,false);
 }else{
   document.attachEvent("onkeydown",keyCapt); //code for IE
   document.attachEvent("onkeyup",keyCapt); 
   document.attachEvent("onkeypress",keyCapt); 
 }
 function keyCapt(e){
   if(typeof window.event!="undefined"){
    e=window.event;//code for IE
   }
   if(e.type=="keydown"){
    t_cel[0].innerHTML=e.keyCode;
    t_cel[3].innerHTML=e.charCode;
   }else if(e.type=="keyup"){
    t_cel[1].innerHTML=e.keyCode;
    t_cel[4].innerHTML=e.charCode;
   }else if(e.type=="keypress"){
    t_cel[2].innerHTML=e.keyCode;
    t_cel[5].innerHTML=e.charCode;
   }
 }
 window.onload=function(){
   t_cel=document.getElementById("tblOne").getElementsByTagName("td");
   tc_ln=t_cel.length;
 }
 </script>
 </head>
 <body>
 <table id="tblOne">
 <tr>
 <th style="border:none;"></th><th>onkeydown</th><th>onkeyup</th><th>onkeypress</td>
 </tr>
 <tr>
 <th>keyCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 <tr>
 <th>charCode</th><td>&nbsp;</td><td>&nbsp;</td><td>&nbsp;</td>
 </tr>
 </table>
 <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>
 </body>
 </html>

Aqui está uma demonstração de trabalho para que você possa experimentá-lo aqui:

var t_cel, tc_ln;
if (document.addEventListener) { //code for Moz
  document.addEventListener("keydown", keyCapt, false);
  document.addEventListener("keyup", keyCapt, false);
  document.addEventListener("keypress", keyCapt, false);
} else {
  document.attachEvent("onkeydown", keyCapt); //code for IE
  document.attachEvent("onkeyup", keyCapt);
  document.attachEvent("onkeypress", keyCapt);
}

function keyCapt(e) {
  if (typeof window.event != "undefined") {
    e = window.event; //code for IE
  }
  if (e.type == "keydown") {
    t_cel[0].innerHTML = e.keyCode;
    t_cel[3].innerHTML = e.charCode;
  } else if (e.type == "keyup") {
    t_cel[1].innerHTML = e.keyCode;
    t_cel[4].innerHTML = e.charCode;
  } else if (e.type == "keypress") {
    t_cel[2].innerHTML = e.keyCode;
    t_cel[5].innerHTML = e.charCode;
  }
}
window.onload = function() {
  t_cel = document.getElementById("tblOne").getElementsByTagName("td");
  tc_ln = t_cel.length;
}
td,
th {
  border: 2px solid #aaa;
}
<html>

<head>
  <title>Untitled</title>
  <meta http-equiv="content-type" content="text/html; charset=iso-8859-1">
</head>

<body>
  <table id="tblOne">
    <tr>
      <th style="border:none;"></th>
      <th>onkeydown</th>
      <th>onkeyup</th>
      <th>onkeypress</td>
    </tr>
    <tr>
      <th>keyCode</th>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
    <tr>
      <th>charCode</th>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
      <td>&nbsp;</td>
    </tr>
  </table>
  <button onclick="for(i=0;i<tc_ln;i++){t_cel[i].innerHTML='&nbsp;'};">CLEAR</button>
</body>

</html>

Uau, é muito simples. eu sou culpa para escrever isso, por que ninguém fazer isso antes?

$(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);       
    });
});

Solução em ES6 para navegadores modernos e IE11 (com transpilation para ES5):

//Disable default IE help popup
window.onhelp = function() {
    return false;
};
window.onkeydown = evt => {
    switch (evt.keyCode) {
        //ESC
        case 27:
            this.onEsc();
            break;
        //F1
        case 112:
            this.onF1();
            break;
        //Fallback to default browser behaviour
        default:
            return true;
    }
    //Returning false overrides default browser event
    return false;
};

Tente esta solução se funciona.

window.onkeypress = function(e) {
    if ((e.which || e.keyCode) == 116) {
        alert("fresh");
    }
}

Quando você usa angularjs para manipulação de eventos, você deve usar ng-keydown para prevenir pause in developer em cromo.

Isso funciona para mim.

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

F2 - 113, F3 - 114, F4 - 115, e assim forte.

Um dos problemas em armadilhas as teclas F1 a F12 é que a função padrão também deve ser substituído . Aqui está um exemplo de uma implementação da chave 'Help' F1 , com a substituição que impede o padrão de ajuda pop-up. Esta solução pode ser estendido para as teclas de F2-F12 . Além disso, este exemplo propositadamente não teclas de combinação não captura , mas isso pode ser alterado também.

<html>
<head>
<!-- Note:  reference your JQuery library here -->
<script type="text/javascript" src="jquery-1.6.2.min.js"></script>
</head>
<body>
    <h1>F-key trap example</h1>
    <div><h2>Example:  Press the 'F1' key to open help</h2></div>
    <script type="text/javascript">
        //uncomment to prevent on startup
        //removeDefaultFunction();          
        /** Prevents the default function such as the help pop-up **/
        function removeDefaultFunction()
        {
            window.onhelp = function () { return false; }
        }
        /** use keydown event and trap only the F-key, 
            but not combinations with SHIFT/CTRL/ALT **/
        $(window).bind('keydown', function(e) {
            //This is the F1 key code, but NOT with SHIFT/CTRL/ALT
            var keyCode = e.keyCode || e.which;
            if((keyCode == 112 || e.key == 'F1') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Open help window here instead of alert
                alert('F1 Help key opened, ' + keyCode);
                }
            // Add other F-keys here:
            else if((keyCode == 113 || e.key == 'F2') && 
                    !(event.altKey ||event.ctrlKey || event.shiftKey || event.metaKey))
             {
                // prevent code starts here:
                removeDefaultFunction();
                e.cancelable = true;
                e.stopPropagation();
                e.preventDefault();
                e.returnValue = false;
                // Do something else for F2
                alert('F2 key opened, ' + keyCode);
                }
        });
    </script>
</body>
</html>

Eu peguei emprestado um solução similar de um artigo tão relacionado no desenvolvimento deste. Deixe-me saber se isso funcionou para você também.

Você pode fazer isso com jQuery como este:

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

        });

Adicionar um atalho:

$.Shortcuts.add({
    type: 'down',
    mask: 'Ctrl+A',
    handler: function() {
        debug('Ctrl+A');
    }
});

Começar a reagir aos atalhos:

$.Shortcuts.start();

Adicione um atalho para o "outro" lista:

$.Shortcuts.add({
    type: 'hold',
    mask: 'Shift+Up',
    handler: function() {
        debug('Shift+Up');
    },
    list: 'another'
});

Ativar o "outro" lista:

$.Shortcuts.start('another');
Remove a shortcut:
$.Shortcuts.remove({
    type: 'hold',
    mask: 'Shift+Up',
    list: 'another'
});

Parar (desvincular manipuladores de eventos):

$.Shortcuts.stop();


Tutorial:
http://www.stepanreznikov.com/js-shortcuts/

A minha solução para este problema é:

document.onkeypress = function (event) {
    event = (event || window.event);
    if (event.keyCode == 123) { 
         return false;
    }
}

Com o número 123 magia que é o F12 chave.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top