简体   繁体   English

在没有keydown事件的情况下检测CTRL和SHIFT键?

[英]Detect CTRL and SHIFT key without keydown event?

I've been wondering if I can detect CTRL and SHIFT key being pressed WITHOUT using keydown event. 我一直想知道是否可以检测到CTRLSHIFT键没有使用keydown事件。

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. 原因是我在JavaScript中创建了某种Grid Viewer,并且我通过按住CTRLSHIFT键来实现选择不同的项目,因为它在大多数常见的查看器,编辑器等中起作用。

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. 然后我按住CTRLSHIFT并单击该项,但它正常工作,因为没有触发keydown。

Any way of omitting this? 有什么方法可以省略这个吗? Perhaps not, but it can be confusing for customers who will treat it as my own obvious Bug. 也许不是,但对于将其视为我自己明显的Bug的客户来说,这可能会令人困惑。

You don't need any key events at all to detect Shift , Ctrl and Alt when mouse is clicked MDN . 当单击鼠标MDN时,您根本不需要任何键事件来检测ShiftCtrlAlt

The Event object contains this information: Event对象包含以下信息:

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

A demo at jsFiddle . 在jsFiddle演示

These properties can be read also in keyboard event handlers. 这些属性也可以在键盘事件处理程序中读取。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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