用于“Ctrl”/“Shift”+鼠标左键单击的 JavaScript 或 jQuery 事件处理程序

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2485345/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 00:34:44  来源:igfitidea点击:

JavaScript or jQuery event handlers for "Ctrl"/"Shift" + mouse left button click

javascriptjqueryevents

提问by Anton

Is it possible to handle such events as:

是否可以处理以下事件:

  • Ctrl+ mouse left button click;
  • Shift+ mouse left button click;
  • Alt+ mouse left button click by using JavaScript, jQueryor other framework.
  • Ctrl+ 鼠标左键单击;
  • Shift+ 鼠标左键单击;
  • Alt+ 使用JavaScriptjQuery或其他框架单击鼠标左键。

If it is possible, please give a code example for it.

如果可能,请给出一个代码示例。

回答by Nick Craver

You can do something like this (jQuery for the click handler, but any framework works on the part that matters):

你可以做这样的事情(点击处理程序的jQuery,但任何框架都适用于重要的部分):

$(selector).click(function(e) {
  if(e.shiftKey) {
    //Shift-Click
  }
  if(e.ctrlKey) {
    //Ctrl+Click
  }
  if(e.altKey) {
    //Alt+Click
  }
});

Just handle whichever you want inside an ifinside the click handler like I have above.

只需if像我上面那样在点击处理程序内部处理您想要的任何内容。

回答by Dhaval

If you use JQuery plugin called hotkeysyou can handle the special keys below.

如果您使用称为热键的JQuery 插件,您可以处理下面的特殊键。

$(document).bind('keydown', 'Ctrl+c', fn);

回答by Sunny R Gupta

More recently I encountered a problem with using e.ctrlKeyin that, it does not work on MACs. In a Macintosh, the same effect is achieved using Command+Click.

最近我遇到了一个问题e.ctrlKey,它在 MAC 上不起作用。在 Macintosh 中,使用 Command+Click 可实现相同的效果。

Since most of the answers above are already assuming usage of jQuery, you can simply use the e.metaKeyproperty which is made available by jQuery.

由于上面的大多数答案已经假设使用 jQuery,因此您可以简单地使用e.metaKeyjQuery 提供的属性。

e.g.

例如

$(selector).click(function(e) {
  if(e.shiftKey) {
    //Shift-Click
  }
  if(e.metaKey) {
    //Ctrl+Click on Windows & Command+Click on Mac.
  }
  if(e.altKey) {
    //Alt+Click
  }
});