admin管理员组文章数量:1287627
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?
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?
Share Improve this question edited Sep 13, 2011 at 9:04 Jasper 2,1764 gold badges31 silver badges51 bronze badges asked Jan 15, 2010 at 22:06 user7289user7289 34.4k29 gold badges75 silver badges88 bronze badges3 Answers
Reset to default 8The 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 plex (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.
Look on this page about keyboard shortcuts to a web application. This site supplies a .js that performs this functionality.
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.
本文标签: javascriptRuby on Rails keyboard shortcutsStack Overflow
版权声明:本文标题:javascript - Ruby on Rails keyboard shortcuts - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741232397a2362347.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论