Ruby on Rails键盘快捷键 [英] Ruby on Rails keyboard shortcuts
问题描述
有谁知道如何在我的网站上使用Ruby on Rails设置键盘快捷键?例如,如果用户想要使用键盘快捷键与站点进行交互而不是单击按钮/链接,我该怎么做?
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?
推荐答案
最简单的方法是为元素设置 accesskey
属性的值。如果您想通过Rails执行此操作,可以通过将额外选项传递给 submit_tag
帮助程序方法来完成此操作,如下所示:
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" />
当 Alt + <时,会导致该按钮被点击按下kbd> R (或 Alt + Shift + R ,具体取决于您的浏览器)。 accesskey
属性适用于< input>
,< button>
和< a>
HTML元素。
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.
如果您想要做更复杂的事情(比如GMail的键盘快捷键,例如),你将不得不写一些javascript。它的核心是一个事件处理程序,它监视文档上的按键,然后调用其他javascript函数来运行按下某个键时所需的代码。这是一种基于按键设置快捷方式的非常简单的方法(这使用Prototype,这是Rails默认使用的Javascript库,并且未经测试):
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;
// ...
}
});
这是另一个SO 问题。
请注意,这些解决方案都不依赖于Rails一点都没。
Note that neither of these solutions really rely on Rails at all.
这篇关于Ruby on Rails键盘快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!