How do I prevent scrolling with arrow keys but NOT the mouse?

时光毁灭记忆、已成空白 提交于 2019-11-27 18:44:50
TheVillageIdiot

Adding document level keypress handler does the trick!

var ar=new Array(33,34,35,36,37,38,39,40);

$(document).keydown(function(e) {
     var key = e.which;
      //console.log(key);
      //if(key==35 || key == 36 || key == 37 || key == 39)
      if($.inArray(key,ar) > -1) {
          e.preventDefault();
          return false;
      }
      return true;
});

Under some circumstances, eg. when you don't actualy have an element you focus on, just some area you had to click, you might not have too much control over the handler and preventing the event at the global level can be a little flaky at best (as I found out the hard way).

The simplest solution in those cases is to bind on the click even of the control button and focus on a empty input element which you position -9000px to the left.

You can then reliably block the event via keydown and also dont have to worry about blocking default behavior or other global listeners since the default behavior on the input element will just move the cursor to the left and right.

If you add a document level keypress handler it will prevent normal scroll on the page at any time, not only when your element has the focus, this might be an undesired effect.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!