does anyone know how to set-up keyboard shortcuts using Ruby on Rails on my website? For example if a user want to interact with the site using keyboard shortcuts instead of clicking buttons/links how would I do this?
问题:
回答1:
The simplest way is to set a value for the accesskey
attribute for your elements. If you wanted to do this through Rails, you could do this by passing an extra option to the submit_tag
helper method, like so:
<%= submit_tag("Save and Refresh", :accesskey => "R") %>
// Equivalent to <input type="submit" value="Save and Refresh" accesskey="R" />
Which will cause that button to be "clicked" when Alt+R (or Alt+Shift+R, depending on your browser) is pressed. The accesskey
attribute is available for <input>
, <button>
and <a>
HTML elements.
If you are looking to do something more complex (like GMail's keyboard shortcuts, for example), you will have to write some javascript. The core of it would be an event handler that watches for keypresses on the document, and then calls other javascript functions to run the code that you want when a certain key is pressed. Here's a very simplistic way of setting up shortcuts based on a key press (this uses Prototype, which is the Javascript library that Rails uses by default, and is untested):
$(document.body).observe("keypress", function(event)
{
var keyCode = event.which || event.keyCode; // W3C and Microsoft's event models
// have differing ways of
// determining which key was pressed
var keyChar = String.fromCharCode(keyCode); // turn a code into an actual character
switch (keyChar)
{
case 'a':
// Run code if the user presses 'a'
break;
// ...
}
});
Here is another SO question that deals with keyboard shortcuts in Javascript.
Note that neither of these solutions really rely on Rails at all.
回答2:
Look on this page about keyboard shortcuts to a web application. This site supplies a .js that performs this functionality.
回答3:
You can use any JavaScript library to provide keyboard shortcuts. Since Rails uses Prototype by default (for the JavaScript helper methods), you might want to check out prototype-hotkeys.
There are some usage examples in that website.