拦截按键像空格和箭头时,停止页面滚动 [英] Stop page from scrolling when intercepting key presses like space and arrows

查看:141
本文介绍了拦截按键像空格和箭头时,停止页面滚动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用JavaScript和Prototype并捕获用户的按键。我成功地捕获了返回,空格和箭头,代码如下:

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

我的问题是空格和箭头继续滚动页面。有没有办法阻止他们滚动页面?

解决方案

原型文档


事件。停止(事件) ACK停止事件的传播,并阻止其
默认动作最终被触发


所以在 break之前添加 Event.stop(e); 应该解决你的问题



此外,您应该为 keydown 事件执行此操作,因为 keyup 太晚了。


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?

解决方案

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.

这篇关于拦截按键像空格和箭头时,停止页面滚动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆