最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

keyboard shortcuts - How to handle ctrl+arrow in Javascript? - Stack Overflow

programmeradmin0浏览0评论

I've noticed an problem when trying to catch keyboard shortcut: CTRL + an arrow.

I've handled keydown event. Now when I hold CTRL key then keydown event is fired once. If I hold an arrow (so that now I'm holding CTRL + an arrow) it doesn't fire another event. Is it forbidden from any reason? I guess I've already encountered this problem in Opera a few years ago and there was an option for it in browser.

My results:

  • holding CTRL, press an arrow -- fires event for CTRL and doesn't fire an event for an arrow

  • press CTRL + an arrow at once -- fires one event but only with keycode of CTRL.

  • holding CTRL, press a letter (eg. S) -- works as expected

  • press CTRL + letter (eg. S) -- works as expected

(Results are identical in Chrome and Firefox. Is the behaviour described above a standard?)

I'm using:

  • function OnKeyDown(e) { }
  • e.ctrlKey, e.which properties of event

The question is: what might be the problem?

I've noticed an problem when trying to catch keyboard shortcut: CTRL + an arrow.

I've handled keydown event. Now when I hold CTRL key then keydown event is fired once. If I hold an arrow (so that now I'm holding CTRL + an arrow) it doesn't fire another event. Is it forbidden from any reason? I guess I've already encountered this problem in Opera a few years ago and there was an option for it in browser.

My results:

  • holding CTRL, press an arrow -- fires event for CTRL and doesn't fire an event for an arrow

  • press CTRL + an arrow at once -- fires one event but only with keycode of CTRL.

  • holding CTRL, press a letter (eg. S) -- works as expected

  • press CTRL + letter (eg. S) -- works as expected

(Results are identical in Chrome and Firefox. Is the behaviour described above a standard?)

I'm using:

  • function OnKeyDown(e) { }
  • e.ctrlKey, e.which properties of event

The question is: what might be the problem?

Share Improve this question edited Sep 13, 2011 at 12:40 Jasper 2,1764 gold badges31 silver badges51 bronze badges asked Apr 22, 2010 at 18:46 MartyIXMartyIX 28.6k32 gold badges139 silver badges216 bronze badges
Add a comment  | 

1 Answer 1

Reset to default 17

You should check if the event.ctrlKey flag is true, something like this:

document.getElementById('element').onkeydown = function (e) { 
  e = e || window.event;
  var keyCode = e.keyCode || e.which,
      arrow = {left: 37, up: 38, right: 39, down: 40 };

  if (e.ctrlKey) {
    switch (keyCode) {
      case arrow.left:
      //... handle Ctrl-LeftArrow
      break;
      //...
    }
  }
};

Check an example here.

发布评论

评论列表(0)

  1. 暂无评论