奉上一个键盘按键值的获取思路。希望对大家有帮助。
const key = ref('')
const code = ref('')
const keyCode = ref('')
const modifiers = ref({ shiftKey: false, ctrlKey: false, altKey: false, metaKey: false })
function handleKeydown(event: any) {
event.preventDefault() // 防止默认操作
key.value = event.key
code.value = event.code
keyCode.value = event.keyCode
modifiers.value = {
shiftKey: event.shiftKey,
ctrlKey: event.ctrlKey,
altKey: event.altKey,
metaKey: event.metaKey,
}
}
function handleVirtualKeydown(key: any) {
// 构造一个模拟的事件对象
const event = {
preventDefault: () => { }, // 空函数,因为没有默认行为需要阻止
key: key.label,
code: key.key,
keyCode: key.code,
shiftKey: false,
ctrlKey: false,
altKey: false,
metaKey: false,
}
// 根据需要设置修饰键的状态
// 例如,如果你的虚拟键盘允许模拟修饰键,你可以在这里设置它们的状态
// 调用handleKeydown函数
handleKeydown(event)
}
const activeKeys = ref<string[]>([])
function updateActiveKey(event: any, isActive: any) {
// 防止重复添加相同的按键code
if (isActive && !activeKeys.value.includes(event.code)) {
activeKeys.value.push(event.code)
}
else if (!isActive) {
const index = activeKeys.value.indexOf(event.code)
if (index !== -1)
activeKeys.value.splice(index, 1)
}
}
onMounted(() => {
window.addEventListener('keydown', handleKeydown)
window.addEventListener('keydown', event => updateActiveKey(event, true))
window.addEventListener('keyup', event => updateActiveKey(event, false))
})
onUnmounted(() => {
window.removeEventListener('keydown', handleKeydown)
window.removeEventListener('keydown', event => updateActiveKey(event, true))
window.removeEventListener('keyup', event => updateActiveKey(event, false))
})