問題描述
如何使用 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 '?', '?', 'ü'
以上鍵只是示例表示.
這篇關于你如何判斷大寫鎖定是否在使用 JavaScript?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!