0

在我的 JavaScript 中,我需要捕捉键盘事件。
但是,当按下某些键时,浏览器会执行某些操作,例如如果按下退格键则转到上一页,或者如果按下则滚动到页面底部spacebar

我可以通过例如捕获keydown事件并调用来停止这些浏览器操作event.preventDefault()。但是,如果我调用event.preventDefault()事件keydownkeypress并且keyup事件永远不会发生。

我需要能够阻止keydown事件的默认浏览器行为,并且在它们被释放时仍然捕获相同的键。我怎样才能做到这一点?

4

1 回答 1

3

However, if I call event.preventDefault() on the keydown event the keypress and keyup events never occur.

You didn't cancel the events themselves, you just cancelled the browser default actions (i.e. the default registered event handlers) with preventDefault - which is exactly what you wanted - but you now want to specify your own keyup and/or keypress event handler, right? The events keyup and keypress are still there, it's just that they probably have no event handlers. Perfect! So now of course "nothing happens" - you took the default event handlers out like you wanted to for "keydown" event, and there were probably no other event handlers registered to the keyup and keypress events so there were no more actions (handlers) to fire anymore!

So from your same event keydown handler, right after you call event.preventdefault(), you can say $('#whatever').on('keyup',function(){console.log('key is up now')}) for example. I mean just bind keyup directly now from same keydown handler to whatever function you desire and I believe that when key goes up it should actually fire that function (i.e. event handler) that you bound to that event.

于 2012-09-10T13:35:07.483 回答