如何使用jQuery单击事件期间检查是否按下了键?

我想用jQuery捕获click事件,并能够判断是否同时按下了一个键,因此我可以基于keypress事件在回调函数中派生。


例如:


$("button").click(function() {

    if([KEYPRESSED WHILE CLICKED]) {

        // Do something...

    } else {

        // Do something different...

    }

});

这是完全可能的,或者如果可能的话怎么办?


撒科打诨
浏览 697回答 3
3回答

慕桂英3389331

您可以从事件属性中轻松检测出shift键,alt键和控制键。$("button").click(function(evt) {  if (evt.ctrlKey)    alert('Ctrl down');  if (evt.altKey)    alert('Alt down');  // ...});有关更多属性,请参见quirksmode。

阿晨1998

您需要使用keydown()和分别跟踪键状态keyup():var ctrlPressed = false;$(window).keydown(function(evt) {  if (evt.which == 17) { // ctrl    ctrlPressed = true;  }}).keyup(function(evt) {  if (evt.which == 17) { // ctrl    ctrlPressed = false;  }});请参阅按键代码列表。现在您可以检查:$("button").click(function() {  if (ctrlPressed) {    // do something  } else {    // do something else  }});

万千封印

我可以单独使用它&nbsp;<a&nbsp; href="" onclick="return Show(event)"></a>&nbsp; function Show(event) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if (event.ctrlKey) {&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;alert('Ctrl down');&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp;}
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JQuery