如何使用jQuery单击事件期间检查是否按下了键?
问题描述:
我想用jQuery捕获click事件,并能够判断是否同时按下了一个键,这样我就可以基于keypress事件在回调函数中进行分叉.
I would like to catch a click event with jQuery and be able to tell if a key was pressed at the same time so I can fork within the callback function based on the keypress event.
例如:
$("button").click(function() {
if([KEYPRESSED WHILE CLICKED]) {
// Do something...
} else {
// Do something different...
}
});
这完全有可能吗?如果有可能怎么办?
Is this possible at all or how can it be done if it is possible?
答
您可以轻松地从事件属性中检测shift,alt和control键;
You can easily detect the shift, alt and control keys from the event properties;
$("button").click(function(evt) {
if (evt.ctrlKey)
alert('Ctrl down');
if (evt.altKey)
alert('Alt down');
// ...
});
有关更多属性,请参见 quirksmode .如果要检测其他键,请参见
See quirksmode for more properties. If you want to detect other keys, see cletus's answer.