如何阐明 ALT+CTRL 和 ALTGR 按键?
我在此处找到此代码作为可能的解决方案,但它不起作用:
if (event.ctrlKey && event.altKey) {
}
此代码适用于 alt+ctr 和 altGr。
我有这样的情况:对于alt+ctrl+e(例如e,没关系)我想要一件事并且对于 altGr+e 另一个,我该怎么做?
如果有人有什么想法,请告诉我。
最佳答案
您可以通过 location
的值检测按下哪个键(从右键或左键)属性(property) event
目的。如果 location 属性的值为 1 ( e.location=1
),则按下左键。如果值为 2,则按下右键。
我在这里为 RightAlter+RightCtrl+<any_valid_key>
提供了我的代码
检查这个例子
var isRightAltKey=false;
var isRightCtrlKey=false;
var validKeys=['a','s','d','f','g']; //keep empty array if no need to check key
document.addEventListener("keydown", function(e) {
if(e.key=="Alt"){
// when right Alter pressed make isRightAltKey true
isRightAltKey= (e.location==2);
}
else if(e.key=="Control"){
// when right Control pressed make isRightCtrlKey true,
//if you need any ctrl key pressed then simply set isRightCtrlKey= true;
isRightCtrlKey= (e.location==2);
}
// checking both right key is pressed already or not?
var isRightKeys= isRightAltKey && isRightCtrlKey;
// validate other keys [optional]
var isValidKey=((typeof validKeys === "undefined") || validKeys.length==0 || validKeys.indexOf(e.key.toLowerCase())>=0);
if (isRightKeys && isValidKey){
document.getElementById("detect_key").innerHTML = "RightAlt + RightCtrl + "+e.key;
}
else
{
document.getElementById("detect_key").innerHTML="";
}
}, false);
document.addEventListener("keyup", function(e) {
if(e.key=="Alt"){
// when right Alter released make isRightAltKey false
isRightAltKey= false;
}
else if(e.key=="Control"){
// when right Control released make isRightCtrlKey false
isRightCtrlKey= false;
}
}, false);
<div id="detect_key"></div>
为什么要附加 keyup 事件监听器?
这里我们必须检测按下 Ctrl 和 Alt 键时的键位置(在 keydown 事件上)。我们必须将它存储在标志变量中并使其为真。释放键时(在 keyup 事件上)必须标记为 false。否则,这些标志始终保持为真。在下一个按键上它永远是真的
关于javascript - 使用 JavaScript 检测 AltGr 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28158262/