Ruby on Rails 键盘快捷键

时间:2023-01-06
本文介绍了Ruby on Rails 键盘快捷键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

有人知道如何在我的网站上使用 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+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;

    // ...
  }
});

这是另一个处理 Javascript 中的键盘快捷键的 SO 问题.

Here is another SO question that deals with keyboard shortcuts in Javascript.

请注意,这些解决方案都没有真正依赖 Rails.

Note that neither of these solutions really rely on Rails at all.

这篇关于Ruby on Rails 键盘快捷键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:如何抵消固定导航栏将我带到的位置? 下一篇:React Navigation 切换背景颜色和样式 StackNavigator

相关文章

最新文章