js实现多个按键组合键监听(实现快捷键)

732 阅读1分钟

这篇文章简单记录一下监听多个按键被同时按下后进行指定操作的思路,例如ctrl+鼠标左键多选,ctrl+shift+滚轮放大缩小指定元素

1、ctrl+鼠标左键多选

<div @click="chooseNode(1)"></div>
<div @click="chooseNode(2)"></div>
<div @click="chooseNode(3)"></div>

点击事件触发时判断是否有按下ctrl

let nodeList = []
const chooseNode = (node) => {
    if(!window.event.ctrlKey) {
        return
    }
    nodeList.push(node)
}

2、ctrl+shift+滚轮

<div @wheel="wheelEvent" :style="{scale: scale / 100}"></div>

创建键盘组合键监听器,将监听到的记录存入combinationKey,并在keyup时清除记录

let combinationKey = []
let saveKeyNum = 2
document.body.addEventListener('keydown', function(event) {
    if(!isArray(combinationKey)) {
        combinationKey = new Array(saveKeyNum).fill(null)
    }
    if(event?.keyCode != combinationKey[combinationKey.length - 1]){
        combinationKey.shift()
        combinationKey.push(event.keyCode)
    }
});
document.body.addEventListener('keyup', function(event) {
    combinationKey = new Array(saveKeyNum).fill(null)
})

判断键盘历史组合键combinationKey是否有ctrl和shift键

const findCombinationKey = (arr, subArr) => {
    let arrIndex = arr.length - 1;
    let subArrIndex = subArr.length - 1;

    while (subArrIndex >= 0 && arrIndex >= 0) {
        if (arr[arrIndex] !== subArr[subArrIndex]) {
            return false;
        }
        arrIndex--;
        subArrIndex--;
    }
    return true;
}
const keyList = [17, 16]
const wheelEvent = (e) => {
    if(!findCombinationKey(combinationKey, keyList)) {
        return
    }
    if (e.wheelDeltaY < 0) {
        changeScale(-1)
    } else {
        changeScale(1)
    }
}
const scale = 100
const changeScale = (step) => {
    scale = scale + step
    if (scale < 10) {
        scale = 10
    }
    if (scale > 200) {
        scale = 200
    }
}