Mis*_*hko 73 html javascript jquery firefox3.6
如何在以下代码中识别按下了哪些 Ctrl/Shift/ Alt键?
$("#my_id").click(function() {
if (<left control key is pressed>) { alert("Left Ctrl"); }
if (<right shift and left alt keys are pressed>) { alert("Right Shift + Left Alt"); }
});
Run Code Online (Sandbox Code Playgroud)
Joh*_*ock 67
嗯,你这不会在IE 8的所有浏览器中工作.微软实现了确定按下哪个(右/左)键的能力.这是一个链接http://msdn.microsoft.com/en-us/library/ms534630(VS.85).aspx
我还在浏览器中发现了这篇关于keypress,keyup,keydown事件的奇妙文章. http://unixpapa.com/js/key.html
$('#someelement').bind('click', function(event){
if(event.ctrlKey) {
if (event.ctrlLeft) {
console.log('ctrl-left');
}
else {
console.log('ctrl-right');
}
}
if(event.altKey) {
if (event.altLeft) {
console.log('alt-left');
}
else {
console.log('alt-right');
}
}
if(event.shiftKey) {
if (event.shiftLeft) {
console.log('shift-left');
}
else
{
console.log('shift-right');
}
}
});
Run Code Online (Sandbox Code Playgroud)
jAn*_*ndy 38
$('#someelement').bind('click', function(event){
if(event.ctrlKey)
console.log('ctrl');
if(event.altKey)
console.log('alt');
if(event.shiftKey)
console.log('shift');
});
Run Code Online (Sandbox Code Playgroud)
我不知道是否可以在点击事件中检查左/右键,但我不认为这是可能的.
您现在也可以使用MouseEvent.getModifierState()它 -截至撰写本文时大多数浏览器都支持它。
document.addEventListener("click", (evn) => {
const shift = evn.getModifierState("Shift");
const ctrl = evn.getModifierState("Control");
const alt = evn.getModifierState("Alt");
console.log("Mouse pressed! Modifiers:");
console.table({shift, ctrl, alt});
});
Run Code Online (Sandbox Code Playgroud)
shift、ctrl和以外的修饰符alt。然而,由于固有的平台差异,不同操作系统的具体行为有些不稳定。使用它们之前请先检查此处。e.originalEvent.location左键返回1,右键返回2.因此,您可以检测到modifier按下了哪个键,如下所示.希望这会帮助你.
var msg = $('#msg');
$(document).keyup(function (e) {
if (e.keyCode == 16) {
if (e.originalEvent.location == 1)
msg.html('Left SHIFT pressed.');
else
msg.html('Right SHIFT pressed.');
} else if (e.keyCode == 17) {
if (e.originalEvent.location == 1)
msg.html('Left CTRL pressed.');
else
msg.html('Right CTRL pressed.');
} else if (e.keyCode == 18) {
if (e.originalEvent.location == 1)
msg.html('Left ALT pressed.');
else
msg.html('Right ALT pressed.');
e.preventDefault(); //because ALT focusout the element
}
});Run Code Online (Sandbox Code Playgroud)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Press modifier key: </label>
<strong id="msg"></strong>Run Code Online (Sandbox Code Playgroud)
小智 5
在大多数情况下ALT,CTRL和SHIFT关键布尔将工作,看是否被按这些键.例如:
var altKeyPressed = instanceOfMouseEvent.altKey
Run Code Online (Sandbox Code Playgroud)
当被调用时,它将返回true或false.有关详细信息,请访问https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/altKey
为了将来参考,还有一个叫metaKey(仅限NS/firefox),当按下元键时它可以工作.