开发者

Ruby on Rails keybard shortcuts [duplicate]

This question already has answers here: Closed 12 years ago.

Possible Duplicate:

Ruby on Rails keybard shortcuts

Hi all - 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?

Any help is greatly appreciated.

Max.


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.


Lokk at this site that is about rails and provides a .js to use keyboard shortcuts on a application.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜