問題描述
有人知道如何在我的網(wǎng)站上使用 Ruby on Rails 設(shè)置鍵盤快捷鍵嗎?例如,如果用戶想使用鍵盤快捷鍵而不是單擊按鈕/鏈接與網(wǎng)站交互,我該怎么做?
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
屬性設(shè)置一個(gè)值.如果你想通過 Rails 做到這一點(diǎn),你可以通過向 submit_tag
輔助方法傳遞一個(gè)額外的選項(xiàng)來做到這一點(diǎn),如下所示:
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" />
當(dāng) Alt+R(或 Alt+Shift 時(shí),這將導(dǎo)致該按鈕被點(diǎn)擊"+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.
如果您想要做一些更復(fù)雜的事情(例如 GMail 的鍵盤快捷鍵),您將不得不編寫一些 javascript.它的核心是一個(gè)事件處理程序,它監(jiān)視文檔上的按鍵,然后在按下某個(gè)鍵時(shí)調(diào)用其他 javascript 函數(shù)來運(yùn)行您想要的代碼.這是一種基于按鍵設(shè)置快捷方式的非常簡單的方法(它使用 Prototype,這是 Rails 默認(rèn)使用的 Javascript 庫,未經(jīng)測(cè)試):
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;
// ...
}
});
這是另一個(gè)處理 Javascript 中的鍵盤快捷鍵的 SO 問題.
Here is another SO question that deals with keyboard shortcuts in Javascript.
請(qǐng)注意,這些解決方案都沒有真正依賴 Rails.
Note that neither of these solutions really rely on Rails at all.
這篇關(guān)于Ruby on Rails 鍵盤快捷鍵的文章就介紹到這了,希望我們推薦的答案對(duì)大家有所幫助,也希望大家多多支持html5模板網(wǎng)!