Stop page from scrolling when intercepting key pre

2019-03-27 14:26发布

I'm using JavaScript and Prototype and catching the key presses from the user. I successfully catch return, space and arrows with code like this:

Event.observe(window, "keyup", function(e) {
  switch (e.keyCode) {
    case Event.KEY_RETURN:
    case Event.KEY_RIGHT:
    case 32:  // space
      // do something
      break;
  }
});

My problem is that spaces and arrow keep on scrolling the page. Is there a way to keep them from scrolling the page?

4条回答
闹够了就滚
2楼-- · 2019-03-27 14:58

It's too late in keyup to prevent the default browser action. Do it in the keydown event instead and use Prototype's Event.stop method:

Event.observe(document, "keydown", function(e) {
  switch (e.keyCode) {
    case Event.KEY_RETURN:
    case Event.KEY_RIGHT:
    case 32:  // space
      // do something
      Event.stop(e);
      break;
  }
});
查看更多
疯言疯语
3楼-- · 2019-03-27 15:05

e.preventDefault() works in Chrome.

查看更多
对你真心纯属浪费
4楼-- · 2019-03-27 15:16

Use e.preventDefault() to Stop default behavior of browser

查看更多
做自己的国王
5楼-- · 2019-03-27 15:18

From the Prototype documentation:

Event.stop(event)
Stops the event’s propagation and prevents its default action from being triggered eventually.

So adding Event.stop(e); before the break; should solve your problem.

Also, you should be doing this for the keydown event, because keyup is too late.

查看更多
登录 后发表回答