Angular 7如何检查任何元素是否有焦点



我希望在keyup上触发一个对话框函数,只要没有集中的输入。我到处找了找,还没有找到解决办法。

我尝试过document.hasFocus((,但没有成功。不管怎样,该功能都会触发。

有什么想法吗?

@HostListener('window:keydown', ['$event'])
handleKeyboardEvent(event: KeyboardEvent) {
if (this.router.url.includes('cart') || this.router.url.includes('rack') || document.hasFocus()) {
console.log(document.activeElement);
return;
}
const dialogConfig = new MatDialogConfig();
dialogConfig.disableClose = false;
dialogConfig.hasBackdrop = true;
const input = String.fromCharCode(event.keyCode);
if (this.search === '' && /[a-zA-Z0-9]/.test(input)) {
this.search = event.key;
dialogConfig.data = this.search;
const dialogRef = this.dialogService.openDialog(SearchBarComponent, dialogConfig);
dialogRef.afterClosed().subscribe(
data => this.search = ''
);
}
}

我想明白了。

我只需要检查activeElement是否就是主体。

document.activeElement === document.body

最新更新