使用JavaScript捕获Shift键活动

时间:2022-12-06 17:25:15

I am using JavaScript and jQuery and would like to call a function when the user releases the Shift key. The code I came up with works in all the browsers I've tested so far, however the following warning appears in the error console using Firefox 3.5.7. I've tried jQuery 1.2.6, 1.3.2 and 1.4.1.

我正在使用JavaScript和jQuery,并希望在用户释放Shift键时调用一个函数。我提出的代码在我到目前为止测试的所有浏览器中都有效,但是使用Firefox 3.5.7在错误控制台中出现以下警告。我已经尝试过jQuery 1.2.6,1.3.2和1.4.1。

Warning: The 'charCode' property of a keyup event should not be used. The value is meaningless.

警告:不应使用keyup事件的'charCode'属性。价值毫无意义。

I searched Google for this warning but could not find a definitive answer as to how to prevent it from happening. This is the code I'm using, does anyone have any suggestions?

我在Google上搜索了此警告,但无法找到关于如何防止它发生的明确答案。这是我正在使用的代码,有没有人有任何建议?

$(document).ready(
  function() {
    $(document).keyup(function(e) {
      if(e.keyCode == 16) {
        alert("Do something...");
      }
    });
  }
);

3 个解决方案

#1


0  

the charCode might be used by jQuery (since you aren't using it). In that case you shouldn't really care about the error message.

jQuery可能会使用charCode(因为你没有使用它)。在这种情况下,您不应该真正关心错误消息。

#2


2  

You could not use jQuery. This is pretty simple without it:

你不能使用jQuery。没有它,这很简单:

document.onkeyup = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 16) {
        alert("Shift");
    }
};

Note that some older browsers (Safari prior to version 3.1, Firefox prior to version 1.0) don't fire keyup events for modifier keys such as Shift.

请注意,某些较旧的浏览器(版本3.1之前的Safari,版本1.0之前的Firefox)不会触发Shift等修饰键的键盘事件。

#3


0  

You need to consider cross-browsers issues as well, see the cross browser solution here:

您还需要考虑跨浏览器问题,请参阅此处的跨浏览器解决方案:

http://cross-browser.com/x/examples/shift_mode.php

#1


0  

the charCode might be used by jQuery (since you aren't using it). In that case you shouldn't really care about the error message.

jQuery可能会使用charCode(因为你没有使用它)。在这种情况下,您不应该真正关心错误消息。

#2


2  

You could not use jQuery. This is pretty simple without it:

你不能使用jQuery。没有它,这很简单:

document.onkeyup = function(evt) {
    evt = evt || window.event;
    if (evt.keyCode == 16) {
        alert("Shift");
    }
};

Note that some older browsers (Safari prior to version 3.1, Firefox prior to version 1.0) don't fire keyup events for modifier keys such as Shift.

请注意,某些较旧的浏览器(版本3.1之前的Safari,版本1.0之前的Firefox)不会触发Shift等修饰键的键盘事件。

#3


0  

You need to consider cross-browsers issues as well, see the cross browser solution here:

您还需要考虑跨浏览器问题,请参阅此处的跨浏览器解决方案:

http://cross-browser.com/x/examples/shift_mode.php