文章内容

2025/4/23 2:06:08,作 者: 黄兵

Angular 页面设置快捷键方法

页面原来代码:

<button mat-menu-item type="button" (click)="deleteFakeBot($event)" ...>
    <mat-icon>delete_forever</mat-icon>
    <span>删除伪造爬虫</span>
</button>
<button mat-menu-item (click)="deleteUA($event)">
    <mat-icon>man</mat-icon>
    <span>删除指定 UA</span>
</button>
<button mat-menu-item (click)="deleteIP($event)">
    <mat-icon>network_ping</mat-icon>
    <span>删除指定 IP</span>
</button>

增加快捷键组件代码:

@HostListener('document:keydown.control.alt.d', ['$event'])
handleDeleteFakeBotHotkey(event: KeyboardEvent) {
  event.preventDefault();
  this.deleteFakeBot(new Event('hotkey'));
}

@HostListener('document:keydown.control.alt.u', ['$event'])
handleDeleteUAHotkey(event: KeyboardEvent) {
  event.preventDefault();
  this.deleteUA(new Event('hotkey'));
}

@HostListener('document:keydown.control.alt.i', ['$event'])
handleDeleteIPHotkey(event: KeyboardEvent) {
  event.preventDefault();
  this.deleteIP(new Event('hotkey'));
}
  • ctrl + alt + d:删除伪造爬虫
  • ctrl + alt + u:删除指定 UA
  • ctrl + alt + i:删除指定 IP
使用 @HostListener 可以监听整个文档的按键事件。

new Event('hotkey') 是为了兼容你的按钮事件签名,可以替换为其他自定义事件对象。

当然我们也可以加上快捷键的说明:

<mat-hint class="text-muted">
    快捷键:Ctrl+Alt+D 删除伪造爬虫,Ctrl+Alt+U 删除 UA,Ctrl+Alt+I 删除 IP
</mat-hint>

或者是这样:

<div class="mt-3">
    <small class="text-muted">
        快捷键:<span class="shortcut-key">Ctrl</span> + <span class="shortcut-key">Alt</span> + <span class="shortcut-key">D</span> 删除假冒 Bot
    </small>
</div>

这样就完成了页面设置快捷键的操作。

分享到:

发表评论

评论列表