英文:
How to call a function with a keyboard without focusing on any textbox?
问题
我知道如何通过文本框触发一个函数:
<input onkeyup="if (event.keyCode == 13) check(this)" type="text">
但是如果我没有聚焦在任何文本框上,但仍然需要通过空格键调用一个JavaScript函数,该怎么办?
特定上下文:
我正在尝试编写一个交互式测试,并且我希望用户不仅可以使用页面上的按钮切换到下一个问题:
<button id="nextButton" onclick="nextQuestion()">下一个</button>
而且还可以使用空格键来更快地切换问题。为了实现这一点,我需要在用户按下键盘上的空格键时每次调用 nextQuestion() 函数。
英文:
I know how to trigger a function with a textbox:
<input onkeyup="if (event.keyCode == 13) check(this)" type="text">
But what if I'm not focused on any textboxes, but I still need to call a js function with a space button for example?
Particular context:
I'm trying to write an interactive test, and I want users to be able to switch to the next question not only with the button on the page:
<button id="nextButton" onclick="nextQuestion()">Next</button>
but also with a space button, so they can change questions more quickly. To arrange that, I need to call the nextQuestion() function everytime a user presses space on a keyboard.
答案1
得分: 2
尝试将事件绑定到窗口
window.onkeyup = function(event){
if (event.keyCode== 32) nextQuestion()
}
英文:
Try binding the event to the window
window.onkeyup = function(event){
if (event.keyCode== 32) nextQuestion()
}
答案2
得分: 1
使用jQuery,您可以像这样做:
$(window).keypress(function(e) {
if (e.keyCode == 32 || e.keyCode == 0) {
nextQuestion();
}
});
或者如果您更喜欢原生JavaScript,我建议:
window.addEventListener("keyup", function(e) {
if (e.keyCode == 32) {
nextQuestion();
}
});
英文:
With jquery you can do something like
$(window).keypress(function(e) {
if (e.keyCode == 32 || e.keyCode == 0) {
nextQuestion()
}
});
or if you prefer vanilla javascript i recommend
window.addEventListener("keyup", keyPressed(e));
function keyPressed(e) {
if(e.keyCode == 32) nextQuestion();
}
答案3
得分: 0
可以在body标签或window对象上调用keyup。
$("body").keyup(function(event){
alert("KeyCode is : " + event.keyCode);
if(event.keyCode == 32){ nextQuestion()}
});
英文:
can call keyup on body tag or window object
$("body").keyup(function(event){
alert("KeyCode is : " + event.keyCode);
if(e.keyCode == 32){ nextQuestion()}
});
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论