简体   繁体   中英

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

Since I'm using jQuery, any solution via that would work too. Ideally, I'd like to know both, though.

I already have the arrow keys bound to another function on my page (using jQuery), but having them cause the page to scroll in addition to that, causes me problems.

I may have known this at one time, but I don't remember it anymore.

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.

如果您添加文档级按键处理程序,它将在任何时候阻止页面上的正常滚动,不仅在您的元素具有焦点时,这可能是不希望的效果。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM