JQuery 或 JavaScript:如何确定在单击锚标记超链接时是否按下了 shift 键?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3781142/
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 06:08:07  来源:igfitidea点击:

JQuery or JavaScript: How determine if shift key being pressed while clicking anchor tag hyperlink?

javascriptjquery

提问by Pete Alvin

I have an anchor tag that calls a JavaScript function.

我有一个调用 JavaScript 函数的锚标记。

With or without JQuery how do I determine if the shift key is down while the link is clicked?

使用或不使用 JQuery 如何确定单击链接时 shift 键是否按下?

The following code does NOT work because keypress is only fired if a "real key" (not the shift key) is pressed. (I was hoping it would fire if just the shift key alone was pressed.)

以下代码不起作用,因为只有在按下“真实键”(而不是 shift 键)时才会触发 keypress。(我希望如果只按下 shift 键它会触发。)

var shifted = false;

$(function() {                           
    $(document).keypress(function(e) {
        shifted = e.shiftKey;
        alert('shiftkey='+e.shiftkey);
    });

    $(document).keyup(function(e) {
        shifted = false;
    });
}

...

function myfunction() {
  //shift is always false b/c keypress not fired above
}

回答by hluk

    $(document).on('keyup keydown', function(e){shifted = e.shiftKey} );

回答by Jsinh

Here is the key code for each key stroke in JavaScript. You can use that and detect if the user has pressed the Shift key.

这是 JavaScript 中每个击键的关键代码。您可以使用它并检测用户是否按下了 Shift 键。

backspace           8
tab                 9
enter               13
shift               16
ctrl                17
alt                 18
pause/break         19
caps lock           20
escape              27
page up             33
page down           34
end                 35
home                36
left arrow          37
up arrow            38
right arrow         39
down arrow          40
insert              45
delete              46
0                   48
1                   49
2                   50
3                   51
4                   52
5                   53
6                   54
7                   55
8                   56
9                   57
a                   65
b                   66
c                   67
d                   68
e                   69
f                   70
g                   71
h                   72
i                   73
j                   74
k                   75
l                   76
m                   77
n                   78
o                   79
p                   80
q                   81
r                   82
s                   83
t                   84
u                   85
v                   86
w                   87
x                   88
y                   89
z                   90
left window key     91
right window key    92
select key          93
numpad 0            96
numpad 1            97
numpad 2            98
numpad 3            99
numpad 4            100
numpad 5            101
numpad 6            102
numpad 7            103
numpad 8            104
numpad 9            105
multiply            106
add                 107
subtract            109
decimal point       110
divide              111
f1                  112
f2                  113
f3                  114
f4                  115
f5                  116
f6                  117
f7                  118
f8                  119
f9                  120
f10                 121
f11                 122
f12                 123
num lock            144
scroll lock         145
semi-colon          186
equal sign          187
comma               188
dash                189
period              190
forward slash       191
grave accent        192
open bracket        219
back slash          220
close braket        221
single quote        222

Not all browsers handle the keypress event well, so use either the key up or the key down event, like this:

并非所有浏览器都能很好地处理 keypress 事件,因此使用 key up 或 key down 事件,如下所示:

$(document).keydown(function (e) {
    if (e.keyCode == 16) {
        alert(e.which + " or Shift was pressed");
    }
});

回答by Pointy

For mouse events, I know that in Firefox at least the "shiftKey" property on the event object will tell you if the shift key is down. It's documented at MSDN but I haven't tried it in forever so I don't recall if IE does this right.

对于鼠标事件,我知道在 Firefox 中,至少事件对象上的“shiftKey”属性会告诉您 shift 键是否按下。它记录在 MSDN 上,但我一直没有尝试过,所以我不记得 IE 是否正确执行此操作。

Thus you should be able to check for "shiftKey" on the event object in your "click" handler.

因此,您应该能够在“单击”处理程序中检查事件对象上的“shiftKey”。

回答by tonycoupland

I had a similar problem, trying to capture a 'shift+click' but since I was using a third party control with a callback rather than the standard clickhandler, I didn't have access to the event object and its associated e.shiftKey.

我遇到了类似的问题,试图捕获“shift+click”,但由于我使用的是带有回调的第三方控件而不是标准click处理程序,因此我无法访问事件对象及其关联的e.shiftKey.

I ended up handling the mouse down event to record the shift-ness and then using it later in my callback.

我最终处理了鼠标按下事件来记录移位,然后在我的回调中使用它。

    var shiftHeld = false;
    $('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });

Posted just in case someone else ends up here searching for a solution to this problem.

发布以防万一其他人最终在这里寻找解决此问题的方法。

回答by Chris Van Opstal

The keypressevent isn't triggered by all browsers when you click shiftor ctrl, but fortunately the keydownevent is.

keypress当您单击shift或 时ctrl,并非所有浏览器都会触发该事件,但幸运keydown是该事件是

If you switch out the keypresswith keydownyou might have better luck.

如果你换掉keypresswithkeydown你可能会有更好的运气。

回答by Corey

I have used a method to test if any specific key is pressed by storing the currently pressed key codes in an array:

我使用了一种方法通过将当前按下的键代码存储在数组中来测试是否按下了任何特定键:

var keysPressed = [],
    shiftCode = 16;

$(document).on("keyup keydown", function(e) {
    switch(e.type) {
        case "keydown" :
            keysPressed.push(e.keyCode);
            break;
        case "keyup" :
            var idx = keysPressed.indexOf(e.keyCode);
            if (idx >= 0)
                keysPressed.splice(idx, 1);
            break;
    }
});

$("a.shifty").on("click", function(e) {
    e.preventDefault();
    console.log("Shift Pressed: " + (isKeyPressed(shiftCode) ? "true" : "false"));
});

function isKeyPressed(code) {
    return keysPressed.indexOf(code) >= 0;
}

Here is the jsfiddle

这是jsfiddle

回答by koppor

The excellent JavaScript library KeyboardJShandles all types of key presses including the SHIFT key. It even allows specifying key combinations such as first pressing CTRL+x and then a.

优秀的 JavaScript 库KeyboardJS处理所有类型的按键,包括 SHIFT 键。它甚至允许指定组合键,例如先按 CTRL+x 然后按 a。

KeyboardJS.on('shift', function() { ...handleDown... }, function() { ...handleUp... });

If you want a simple version, head to the answer by @tonycoupland):

如果您想要一个简单的版本,请前往@tonycoupland答案):

var shiftHeld = false;
$('#control').on('mousedown', function (e) { shiftHeld = e.shiftKey });

回答by kaleazy

This works great for me:

这对我很有用:

function listenForShiftKey(e){
    var evt = e || window.event;
    if (evt.shiftKey) {
      shiftKeyDown = true;
    } else {
      shiftKeyDown = false;
    }
}

回答by bugovicsb

For checking if the shiftkey is pressed while clicking with the mouse, there is an exact property in the click event object: shiftKey (and also for ctrl and alt and meta key): https://www.w3schools.com/jsref/event_shiftkey.asp

为了检查在用鼠标单击时是否按下了 shiftkey ,单击事件对象中有一个确切的属性:shiftKey(以及 ctrl 和 alt 和元键):https: //www.w3schools.com/jsref/event_shiftkey .asp

So using jQuery:

所以使用jQuery:

$('#anchor').on('click', function (e) {
    if (e.shiftKey) {
        // your code
    }
});

回答by Rob Fox

A more modular approach plus the ability to keep your thisscope in the listeners:

更模块化的方法以及将this范围保持在侦听器中的能力:

var checkShift = function(fn, self) {
  return function(event) {
    if (event.shiftKey) {
      fn.call(self, event);
    }
    return true;
  };
};

$(document).on('keydown', checkShift(this.enterMode, this));