Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.2k views
in Technique[技术] by (71.8m points)

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

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?

question from:https://stackoverflow.com/questions/65871323/navigate-buttons-using-arrows-in-html

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...