Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

javascript - 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.

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.

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...