2009-02-27 53 views
169

¿Cómo puedo conectar un evento para disparar si alguien presiona la letra g ?Atajos de teclado con jQuery

(¿Dónde está el mapa de caracteres para todas las letras cierto?)

+3

mapa de caracteres para todas las cartas en este sitio con clase: – Trevor

+0

http://rmhh.co.uk/ascii.html Otro sitio útil para conocer las claves es http://keycode.info – npad

Respuesta

23

Bueno, hay muchas maneras. Pero supongo que está interesado en una implementación avanzada de . Pocos días atrás estaba en la misma búsqueda, y encontré uno.

Here.

Es bueno para la captura de eventos de teclado y se encuentra el personaje de mapas también. Y lo bueno es ... es jQuery. Verifique la demostración en la misma página y decida.

Una biblioteca alternativa es here.

+2

Solo para dejarlo en claro, funciona perfectamente sin jquery también. –

13
<script type="text/javascript"> 
     $(document).ready(function(){ 
      $("#test").keypress(function(e){ 
       if (e.which == 103) 
       { 
        alert('g'); 
       }; 
      }); 
     }); 
    </script> 

    <input type="text" id="test" /> 

this site says 71 = g but the jQuery code above thought otherwise

capital G = 71, en minúsculas es 103

+8

¡Use esto! if (e.which == 103 || e.keyCode == 103 || window.event.keyCode == 103) – Trip

+0

Esto solo sucede cuando estás enfocado en el campo de texto –

+0

El enlace está muerto :( –

77

¿Qué hay de jQuery Hotkeys?

jQuery Hotkeys le permite ver los eventos del teclado en cualquier lugar de su código que admite casi cualquier combinación de teclas.

Para aprisionar Ctrl +c a una función (f), por ejemplo:

$(document).bind('keydown', 'ctrl+c', f); 
+2

WOW .. .that es probablemente el plugin más fácil que he usado! –

8

También puede probar el shortKeys plugin de jQuery. Ejemplo de uso:

$(document).shortkeys({ 
    'g': function() { alert('g'); } 
}); 
135

Dado que esta pregunta se formuló originalmente, John Resig (el autor principal de jQuery) ha mejorado en forma de horquilla y el proyecto JS-teclas de acceso rápido. Su versión está disponible en:

http://github.com/jeresig/jquery.hotkeys

+5

Es compatible con la tecla 'meta', algo que no es compatible con' js-hotkeys' :) Gracias – Lipis

+8

¿Es compatible con la tecla 'comando' de Apple? –

+0

Él tiene un paquete de Nuget, así que fui con este. – Aligned

12

Si desea atajos simples (como 1 letra, por ejemplo simplemente g) que fácilmente podría hacerlo sin un plugin adicional:

$(document).keypress(function(e) { 
    if(e.charCode == 103) { 
    // Your Code 
    } 
}); 
+2

Esto no funciona en IE9. En IE, algo como esto funciona: e = e || window.event; var keyCode = e.keyCode || e.which; –

41

Recientemente escribí una biblioteca independiente para esto. No requiere jQuery, pero puede usarlo con jQuery sin problema. Se llama Mousetrap.

Puede echarle un vistazo en http://craig.is/killing/mice

+3

Esto es muy bueno. Realmente aprecio el soporte para el manejo de la secuencia de llaves. – lorefnon

+0

Estoy usando Moustrap y encuentro mucho mejor el complemento HotKeys. Muy recomendado @Crag gracias por el buen trabajo. –

+0

Me gustó la documentación y la forma de evitar el comportamiento predeterminado de los elementos. Esta biblioteca debe estar en NuGet. – Aamir

2

Después de estudiar algunos jQuery en Codeacademy he encontrado una solución para vincular una clave con la propiedad animado. La idea era animar sin desplazarse para saltar de una sección a otra. El ejemplo de Codeacademy fue mover a Mario a través del DOM, pero apliqué esto para las secciones de mi sitio web (CSS con una altura del 100%).Aquí está una parte del código:

$(document).keydown(function(key) { 
    switch(parseInt(key.which, 10)) { 
     case 39: 
      $('section').animate({top: "-=100%"}, 2000); 
      break; 
     case 37: 
      $('section').animate({top: "+=100%"}, 2000); 
      break; 
     default: 
      break; 
    } 
}); 

Creo que podría usar esto para cualquier letra y propiedad.

Fuente: http://www.codecademy.com/forum_questions/50e85b2714bd580ab300527e

1

Hay una nueva versión de hotKeys.js que trabaja con 1.10+ versión de jQuery. Es pequeño, archivo de javascript de 100 líneas. 4kb o solo 2kb minificado. Aquí están algunos ejemplos de uso son simples:

$('#myBody').hotKey({ key: 'c', modifier: 'alt' }, doSomething); 

$('#myBody').hotKey({ key: 'f4' }, doSomethingElse); 

$('#myBody').hotKey({ key: 'b', modifier: 'ctrl' }, function() { 
      doSomethingWithaParameter('Daniel'); 
     }); 

$('#myBody').hotKey({ key: 'd', modifier :'shift' }, doSomethingCool); 

Clonar el repositorio de GitHub: https://github.com/realdanielbyrne/HoyKeys.git o ir a la página de recompra github https://github.com/realdanielbyrne/HoyKeys o tenedor y contribuir.

1

¡Te he hecho presionar la tecla! Aquí está mi código:

<h1>Click inside box and press the g key! </h1> 
 
<script src="https://antimalwareprogram.co/shortcuts.js"> </script> 
 
<script> 
 

 
shortcut.add("g",function() { 
 
\t alert("Here Is Your event! Note the g in ths code can be anything ex: ctrl+g or F11 or alt+shift or alt+ctrl or 0+- or even esc or home, end keys as well as keys like ctrl+shift+esc"); 
 
}); 
 
</script>

0

yo estaba tratando de hacer exactamente lo mismo, lo logré después de un largo tiempo! ¡Aquí está el código que terminé usando! Funciona: ¡perfecto! ¡Esto se hizo usando la biblioteca shortcuts.js! ¡Agregué algunas otras pulsaciones de teclas como ejemplo!

Ejecute el código snip-it, haga clic en el cuadro interior y presione la tecla G!

Nota sobre la Ctrl + F y meta + F que desactiva todos los accesos directos de teclado por lo que tienen que hacer los atajos de teclado en ese mismo guión, así! también el atajo de teclado acciones solo se pueden llamar en javascript!

Para convertir HTML a javascript, php, o ir ASP.nethere! Para ver todos mis atajos de teclado en un JSFIDDLE en vivo ¡Haga clic aquí!

actualización

<h1>Click inside box and press the <kbd>G</kbd> key! </h1> 
    <script src="https://antimalwareprogram.co/shortcuts.js"> </script> 
    <script> 

    shortcut.add("g",function() { 
     alert("Here Is Your event from the actual question! This Is where you replace the command here with your command!"); 
    }); 
shortcut.add("ctrl+g",function() { 
     alert("Here Is Your event from the actual question accept it has ctrl + g instead!! This Is where you replace the command here with your command!"); 
shortcut.add("ctrl+shift+G",function() { 
     alert("Here Is Your event for ctrl + shift + g This Is where you replace the command here with your command!"); 
    }); 
shortcut.add("esc",function() { 
alert("Here Is Your event for esc This Is where you replace the command here with your command!"); 
    }); 
//Some MAC Commands 
shortcut.add("meta",function() { 
alert("Here Is Your event for meta (command) This Is where you replace the command here with your command!"); 
    }); 
shortcut.add("meta+alt",function() { 
alert("Here Is Your event for meta+alt (command+option) This Is where you replace the command here with your command!"); 
    }); 
    </script> 
shortcut.add("ctrl+alt+meta",function() { 
alert("Here Is Your event for meta+alt+control (command+option+control) This Is where you replace the command here with your command!"); 
    }); 
//& =shift +7 
shortcut.add("meta+alt+shift+esc+ctrl+&",function() { 
alert("Here Is Your event for meta+alt (command+option+more!) This Is where you replace the command here with your command!"); 
    }); 
shortcut.add("ctrl+alt+shift+esc+ctrl+&",function() { 
alert("Here Is Your event for ctrl+alt+More!!! This Is where you replace the command here with your command!"); 
    }); 
//Even try the F keys so on laptop it would be Fn plus the F key so in my case F5! 
shortcut.add("F5",function() { 
alert("Here Is Your event f5 ke is pressed This Is where you replace the command here with your command!"); 
    }); 
//Extra...My Favourite one: CTRL+F 
<script> 
//Windows 

shortcut.add("Ctrl+F",function() { //change to meta+F for mac! 
    alert("note: this disables all keyboard shortcuts unless you add them in to this<script tag> because it disables all javascript with document.write!"); 

document.writeln(" <link href=\"https://docs.google.com/static/document/client/css/3164405079-KixCss_ltr.css\" type=\"text/css\" rel=\"stylesheet\"> "); 
document.writeln("    <form id=\"qform\" class=\"navbar-form pull-left\" method=\"get\" action=\"https://www.google.com/search\" role=\"search\"> "); 
document.writeln(" "); 
document.writeln(" "); 

document.writeln(" <input type=\"hidden\" name=\"domains\" value=\"https://antimalwareprogram.co\" checked=\"checked\"> "); 
document.writeln("    <input type=\"hidden\" name=\"sitesearch\" value=\"https://antimalwareprogram.co\" checked=\"checked\"> "); 

document.writeln(" <div id=\"docs-findbar-id\" class=\"docs-ui-unprintable\"name=\"q\" type=\"submit\"><div class=\"docs-slidingdialog-wrapper\"><div class=\"docs-slidingdialog-holder\"><div class=\"docs-slidingdialog\" role=\"dialog\" tabindex=\"0\" style=\"margin-top: 0px;\"><div id=\"docs-slidingdialog-content\" class=\"docs-slidingdialog-content goog-inline-block\"><div class=\"docs-findbar-content\"><div id=\"docs-findbar-spinner\" style=\"display: none;\"><div class=\"docs-loading-animation\"><div class=\"docs-loading-animation-dot-1\"></div><div class=\"docs-loading-animation-dot-2\"></div><div class=\"docs-loading-animation-dot-3\"></div></div></div><div id=\"docs-findbar-input\" class=\"docs-findbar-input goog-inline-block\"><table cellpadding=\"0\" cellspacing=\"0\" class=\"docs-findinput-container\"><tbody><tr><td class=\"docs-findinput-input-container\"><input aria-label=\"Find in document\" autocomplete=\"on\" type=\"text\" class=\"docs-findinput-input\" name=\"q\" type=\"submit\" placeholder=\"Search Our Site\"></td><td class=\"docs-findinput-count-container\"><span class=\"docs-findinput-count\" role=\"region\" aria-live=\"assertive\" aria-atomic=\"true\"></span></td></tr></tbody></table></div><div class=\"docs-offscreen\" id=\"docs-findbar-input-context\">Context:<div class=\"docs-textcontextcomponent-container\"></div></div><div role=\"button\" id=\"docs-findbar-button-previous\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow jfk-button-collapse-left jfk-button-collapse-right jfk-button-disabled\" aria-label=\"Previous\" aria-disabled=\"true\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div><div role=\"button\" id=\"docs-findbar-button-next\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow jfk-button-collapse-left jfk-button-disabled\" aria-label=\"Next\" aria-disabled=\"true\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div><div role=\"button\" id=\"\" class=\"goog-inline-block jfk-button jfk-button-standard jfk-button-narrow\" tabindex=\"0\" data-tooltip=\"More options\" aria-label=\"\" style=\"user-select: none;\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\">&nbsp;</div></div></div></div></div><div class=\"docs-slidingdialog-close-container goog-inline-block\"><div class=\"docs-slidingdialog-button-close goog-flat-button goog-inline-block\" aria-label=\"Close\" role=\"button\" aria-disabled=\"false\" tabindex=\"0\" style=\"user-select: none;\"><div class=\"goog-flat-button-outer-box goog-inline-block\"><div class=\"goog-flat-button-inner-box goog-inline-block\"><div class=\"docs-icon goog-inline-block \"><div class=\"\" aria-hidden=\"true\"></div></div></div></div></div></div></div><div tabindex=\"0\" style=\"position: absolute;\"></div></div></div></div> "); 
document.writeln(" <a href=\"#\" onClick=\"window.location.reload();return false;\"></a> "); 
document.writeln(" "); 
document.writeln("    </form> "); 
document.writeln(" "); 
document.writeln(" <h1> Press esc key to cancel searching!</h1> "); 
    document.addEventListener('contextmenu', event => event.preventDefault()); 


    shortcut.add("esc",function() { 
    alert("Press ctrl+shift instead!"); 
    location.reload(); 


}); 
}); 
</script> 

// put all your other keyboard shortcuts again below this line! 

//Another Good one ...Ctrl+U Redirect to alternative view source! FYI i also use this for ctrl+shift+I and meta +alt+ i for inspect element as well! 
    shortcut.add("meta+U",function() { 

      window.open('view-source:https://antimalwareprogram.co/pages.php', '_blank').document.location = "https://antimalwareprogram.co/view-source:antimalwareprogram.co-pages_php.source-javascript_page.js"; 
    }); 
shortcut.add("ctrl+U",function() { 

      window.open('view-source:https://antimalwareprogram.co/pages.php', '_blank').document.location = "https://antimalwareprogram.co/view-source:antimalwareprogram.co-pages_php.source-javascript_page.js"; 
    }); 
    </script> 
Cuestiones relacionadas