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

javascript - Detect CTRL and SHIFT key without keydown event? - Stack Overflow

programmeradmin2浏览0评论

I've been wondering if I can detect CTRL and SHIFT key being pressed WITHOUT using keydown event.

The reason is that I am creating some sort of Grid Viewer in JavaScript, and I implemented selecting different items by holding CTRL or SHIFT key as it functions in most common viewers, editors and so on.

The problem is that when the focus is not anywhere on the page. For example I'm adding page to the bookmarks. Then I hold CTRL or SHIFT and click on the item, but it acts normally as keydown hasn't been triggered.

Any way of omitting this? Perhaps not, but it can be confusing for customers who will treat it as my own obvious Bug.

I've been wondering if I can detect CTRL and SHIFT key being pressed WITHOUT using keydown event.

The reason is that I am creating some sort of Grid Viewer in JavaScript, and I implemented selecting different items by holding CTRL or SHIFT key as it functions in most common viewers, editors and so on.

The problem is that when the focus is not anywhere on the page. For example I'm adding page to the bookmarks. Then I hold CTRL or SHIFT and click on the item, but it acts normally as keydown hasn't been triggered.

Any way of omitting this? Perhaps not, but it can be confusing for customers who will treat it as my own obvious Bug.

Share Improve this question edited Jul 11, 2014 at 17:27 Anderson 1387 bronze badges asked Aug 19, 2013 at 14:37 FlashFlash 4761 gold badge7 silver badges17 bronze badges 3
  • If they treat it as a bug of yours, that's their fault. If they don't want to focus your page, they don't get your features – Ian Commented Aug 19, 2013 at 14:39
  • 2 You can detect those keys also in onclick handler... – Teemu Commented Aug 19, 2013 at 14:41
  • 1 @Teemu Good point. I'm not sure why the keydown event is being used. Everything should be checked at the clicking point – Ian Commented Aug 19, 2013 at 14:53
Add a comment  | 

1 Answer 1

Reset to default 20

You don't need any key events at all to detect Shift, Ctrl and Alt when mouse is clickedMDN.

The Event object contains this information:

element.addEventListener('click', function (e) {
    console.log(e.shiftKey);
    console.log(e.ctrlKey);
    console.log(e.altKey);
});

A demo at jsFiddle.

These properties can be read also in keyboard event handlers.

发布评论

评论列表(0)

  1. 暂无评论