js簡(jiǎn)單封裝監(jiān)聽(tīng)快捷鍵對(duì)象示例及使用
更新時(shí)間:2023年08月08日 14:43:06 作者:littlesunn
這篇文章主要為大家介紹了js簡(jiǎn)單封裝監(jiān)聽(tīng)快捷鍵對(duì)象及使用示例,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪
js簡(jiǎn)單封裝一個(gè)監(jiān)聽(tīng)快捷鍵的對(duì)象
export default class Shortcuts {
keyCodeMap = new Map([
["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],
["UP", 38],
["RIGHT", 39],
["DOWN", 40],
["LEFT", 37],
["CTRL", 17],
["SHIFT", 16],
["ALT", 18],
["SPACE", 32], // 空格鍵
]);
constructor(keyNames = [], callback, isPreventDefault = false) {
this.destroy();
this.isPreventDefault = isPreventDefault;
this.keyNames = keyNames;
this.callback = callback;
this.initEventListener()
}
initEventListener() {
document.addEventListener("keyup", this.handleKeyup.bind(this))
}
destroy() {
document.removeEventListener("keyup", this.handleKeyup.bind(this))
}
handleKeyup(e) {
this.isPreventDefault && e.preventDefault(); // 是否阻止默認(rèn)行為
let conditions = []
if (Array.isArray(this.keyNames)) { // 數(shù)組是組合鍵
this.keyNames.forEach(code => {
let strCode = code.toString().toUpperCase();
switch (strCode) {
case "CTRL":
conditions.push(e.ctrlKey)
break;
case "SHIFT":
conditions.push(e.shiftKey)
break;
case "ALT":
conditions.push(e.altKey)
break;
default:
conditions.push(this.keyCodeMap.get(strCode) == e.keyCode)
break;
}
})
}else {
let strCode = this.keyNames.toString().toUpperCase();
if(strCode == e.keyCode){
conditions.push(true);
}
}
if (conditions.every(item => item)) {
this.callback && this.callback()
}
}
}使用
new Shortcuts(["ctrl", "q"], ()=>{ //組合鍵
console.log(111);
});
new Shortcuts("q", ()=>{ // 單鍵
console.log(111);
});以上就是js簡(jiǎn)單封裝監(jiān)聽(tīng)快捷鍵對(duì)象示例及使用的詳細(xì)內(nèi)容,更多關(guān)于js封裝監(jiān)聽(tīng)快捷鍵對(duì)象的資料請(qǐng)關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
微信小程序 input輸入及動(dòng)態(tài)設(shè)置按鈕的實(shí)現(xiàn)
這篇文章主要介紹了微信小程序 input輸入及動(dòng)態(tài)設(shè)置按鈕的實(shí)現(xiàn)的相關(guān)資料,希望通過(guò)本文能幫助到大家,需要的朋友可以參考下2017-10-10
直觀詳細(xì)的typescript隱式類型轉(zhuǎn)換圖文詳解
這篇文章主要為大家介紹了直觀詳細(xì)的typescript隱式類型轉(zhuǎn)換圖文詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-07-07

