Skip to content

Commit

Permalink
fix: 输入框聚焦,按下 s 进入搜索面板
Browse files Browse the repository at this point in the history
  • Loading branch information
peng-xiao-shuai committed Apr 29, 2024
1 parent 66adff5 commit d102d8a
Showing 1 changed file with 20 additions and 8 deletions.
28 changes: 20 additions & 8 deletions src/directives/common/press-key.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,20 +21,29 @@ interface keys {
}
const keys: keys = {}

// 判断类型
const ifType = (el: Element): boolean => {
return el.tagName == 'INPUT' || el.tagName == 'TEXTAREA'
/**
* 判断类型
* @param {Element} el
*/
const ifType = (
el: Element | null,
): HTMLInputElement | HTMLTextAreaElement | undefined => {
if (!el) return undefined

const isInput = (el: Element) =>
el.tagName == 'INPUT' || el.tagName == 'TEXTAREA'

if (isInput(el)) return el as HTMLInputElement | HTMLTextAreaElement
else if (el.children.length && isInput(el.children[0]))
return el.children[0] as HTMLInputElement | HTMLTextAreaElement
else undefined
}

export default function pressKey(app: App) {
app.directive('press-key', {
mounted(el, bind) {
// 判断是否是 input 或者 textarea 由于 el-input是一个div元素且它的下级才是input 故此获取children
const inputNode = ifType(el)
? el
: el.children.length && ifType(el.children[0])
? el.children[0]
: undefined

if (!bind.arg) {
console.error('请绑定需要触发的键,例如v-press-key:s')
Expand Down Expand Up @@ -89,12 +98,15 @@ export default function pressKey(app: App) {
}

window.onkeydown = function keydown(event: KeyboardEvent) {
if (ifType(document.activeElement)) {
return
}
// 获取匹配项
const match = Object.keys(keys).filter(
(item) =>
event.key.toUpperCase() == item ||
event.key.toLowerCase() == item ||
event.key == item
event.key == item,
)

match.length && keys[match[0]].funVal()
Expand Down

0 comments on commit d102d8a

Please sign in to comment.