你如何判断大写锁定是否在使用 JavaScript?

2022-01-13 00:00:00 keyboard capslock javascript

如何使用 JavaScript 判断大写锁定是否开启?

How do you tell if caps lock is on using JavaScript?

但有一个警告:我用谷歌搜索了它,我能找到的最佳解决方案是将 onkeypress 事件附加到每个输入,然后每次检查按下的字母是否为大写,如果是,然后检查 shift 是否也被按住.如果不是,则必须打开大写锁定.这感觉真的很脏而且……浪费 - 肯定有比这更好的方法吗?

One caveat though: I did google it and the best solution I could find was to attach an onkeypress event to every input, then check each time if the letter pressed was uppercase, and if it was, then check if shift was also held down. If it wasn't, therefore caps lock must be on. This feels really dirty and just... wasteful - surely there's a better way than this?

推荐答案

你可以试一试.添加了一个工作示例.当焦点放在输入上时,打开大写锁定会使 LED 变为红色,否则变为绿色.(没有在mac/linux上测试过)

You can give it a try.. Added a working example. When focus is on input, turning on caps lock makes the led go red otherwise green. (Haven't tested on mac/linux)

注意:两个版本都适合我.感谢评论中的建设性意见.

NOTE: Both versions are working for me. Thanks for constructive inputs in the comments.

旧版本:https://jsbin.com/mahenes/edit?js,output

另外,这是一个修改版(有人可以在mac上测试并确认)

Also, here is a modified version (can someone test on mac and confirm)

新版本:https://jsbin.com/xiconuv/edit?js,output

新版本:

function isCapslock(e) {
  const IS_MAC = /Mac/.test(navigator.platform);

  const charCode = e.charCode;
  const shiftKey = e.shiftKey;

  if (charCode >= 97 && charCode <= 122) {
    capsLock = shiftKey;
  } else if (charCode >= 65 && charCode <= 90
    && !(shiftKey && IS_MAC)) {
    capsLock = !shiftKey;
  }

  return capsLock;
}

旧版本:

function isCapslock(e) {
  e = (e) ? e : window.event;

  var charCode = false;
  if (e.which) {
    charCode = e.which;
  } else if (e.keyCode) {
    charCode = e.keyCode;
  }

  var shifton = false;
  if (e.shiftKey) {
    shifton = e.shiftKey;
  } else if (e.modifiers) {
    shifton = !!(e.modifiers & 4);
  }

  if (charCode >= 97 && charCode <= 122 && shifton) {
    return true;
  }

  if (charCode >= 65 && charCode <= 90 && !shifton) {
    return true;
  }

  return false;
}

对于国际字符,可以根据需要对以下键添加额外的检查.您必须获取您感兴趣的字符的键码范围,可能是通过使用一个键映射数组来保存您正在处理的所有有效用例键...

For international characters, additional check can be added for the following keys as needed. You have to get the keycode range for characters you are interested in, may be by using a keymapping array which will hold all the valid use case keys you are addressing...

大写 A-Z 或 'Ä'、'Ö'、'Ü'、小写 a-Z 或 0-9 或 'ä'、'ö'、'ü'

uppercase A-Z or 'Ä', 'Ö', 'Ü', lowercase a-Z or 0-9 or 'ä', 'ö', 'ü'

以上键只是示例表示.

相关文章