我有一系列多项选择题:
<div class="question active">
<p>The first counting tool was the _____.</p>
<button class="btn-a">A) Stepped Reckoned</button>
<button class="btn-b">B) Abacus</button>
<button class="btn-c">C) Aba Zaba</button>
<button class="btn-d">D) Punch Card</button>
</div>
<div class="question">
<p>Who founded IBM and was responsible for tabulating the US Census with a punch card tabulator in only six weeks?</p>
<button class="btn-a">A) Jacquard</button>
<button class="btn-b">B) Hollerith</button>
<button class="btn-c">C) Mark I</button>
<button class="btn-d">D) Babbage</button>
</div>
如何触发每个按钮以使用键盘上的相应字母提交?
键盘应仅适用于.active
问题。
加成:
是否可以允许两个键触发问题?例如,由于ABCD
围绕键盘间隔,因此允许QWER
或JKL;
与ABCD
对应以使单手键盘输入变得容易也是有帮助的。
答案 0 :(得分:1)
使用keyup
事件,您可以侦听释放密钥的用户。然后,您可以将其翻译为字母(或我的示例中的箭头键),并访问相应的问题/按钮。你可以尝试这样的事情:
$(document).ready(function () {
var $questions = $("div.question"),
$activeQuestion = function () {
return $questions.filter(".active");
},
$prevQuestion = function (setActive) {
var $prev;
$prev = $activeQuestion().prevAll(".question").first();
if ($prev.length === 0) {
$prev = $questions.last();
}
return $prev;
},
$nextQuestion = function () {
var $next;
$next = $activeQuestion().nextAll(".question").first();
if ($next.length === 0) {
$next = $questions.first();
}
return $next;
};
$(document).on("keyup", function (e) {
var key, character, $active, $next, $prev;
key = e.which;
switch (key) {
case 37:
case 38:
$prev = $prevQuestion();
$questions.removeClass("active");
$prev.addClass("active");
break;
case 39:
case 40:
$next = $nextQuestion();
$questions.removeClass("active");
$next.addClass("active");
break;
default:
character = String.fromCharCode(key).toLowerCase();
$active = $activeQuestion();
$active.find("button").removeClass("selected").filter(".btn-" + character).addClass("selected");
break;
}
});
});
DEMO: http://jsfiddle.net/wdXkB/1/
我把它拿了一点,但我添加了使用箭头键移动到下一个问题(向下和向右箭头)或上一个问题(向上和向左箭头)的能力。