按下空格触发Javascript事件 [英] Javascript event triggered by pressing space
问题描述
当我在页面上并按 space 时,我试图触发一个事件,但我无法弄清楚.目前,我正在尝试使用jQuery来获得令人满意的结果.
I am trying to get an event to trigger when I am on a page and press space, but I can't figure it out. Currently I am trying to use jQuery to accomplish a satisfying result.
我曾尝试使用 keydown
, keyup
和 keypress
,但似乎只有在实际输入一些内容时才能使用它表单或字段.
I have tried using keydown
, keyup
and keypress
, but it seems that you can only use it if you are actually inputting something to a form or field.
我想要的是在按下 space 时触发警报.
What I want is to trigger an alert when space is pressed.
推荐答案
这些事件冒起,因此,如果您试图在焦点所在的地方(即不在输入中)触发该事件,只需将处理程序绑定到窗口
:
These events bubble up, so if you're trying to trigger the event wherever your focus is (ie. not in an input), just bind a handler on window
:
$(window).keypress(function (e) {
if (e.key === ' ' || e.key === 'Spacebar') {
// ' ' is standard, 'Spacebar' was used by IE9 and Firefox < 37
e.preventDefault()
console.log('Space pressed')
}
})
另请参见所有的列表.键
值.
这篇关于按下空格触发Javascript事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!