如何在不聚焦在任何文本框上的情况下使用键盘调用函数?

huangapple go评论68阅读模式
英文:

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:

&lt;input onkeyup=&quot;if (event.keyCode == 13) check(this)&quot; type=&quot;text&quot;&gt;

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:

&lt;button id=&quot;nextButton&quot; onclick=&quot;nextQuestion()&quot;&gt;Next&lt;/button&gt;

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(&quot;keyup&quot;, 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

 $(&quot;body&quot;).keyup(function(event){
      alert(&quot;KeyCode is : &quot; + event.keyCode);
      if(e.keyCode == 32){ nextQuestion()}
    });

huangapple
  • 本文由 发表于 2020年1月3日 21:48:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/59579716.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定