You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中@HostListener监听window:keydown.escape在全屏下不触发如何解决

解决方案

1. 修复esc按键监听不触发的问题

全屏模式下浏览器会将按键事件的作用域绑定到当前处于全屏状态的DOM元素上,而非全局window对象,所以直接监听window的esc事件会失效。你可以将事件绑定到实际全屏的元素上:

// Angular 示例代码
import { ViewChild, ElementRef } from '@angular/core';

export class YourComponent {
  // 获取你用来开启全屏的容器元素
  @ViewChild('fullscreenContainer') fullscreenContainer: ElementRef;

  // 进入全屏逻辑
  enterFullscreen() {
    const el = this.fullscreenContainer.nativeElement;
    el.requestFullscreen?.().then(() => {
      // 给全屏元素绑定esc按键监听,开启捕获阶段触发避免事件被拦截
      el.addEventListener('keydown', this.handleEscPress, true);
    });
  }

  handleEscPress = (e: KeyboardEvent) => {
    if (e.key !== 'Escape') return;
    // 此处写入你需要在全屏退出前执行的操作
    console.log('执行全屏退出前的自定义逻辑');
    
    // 若需要等自定义逻辑执行完成再退出全屏,可开启下面两行代码
    // e.preventDefault();
    // 你的异步逻辑执行完成后,手动调用退出全屏
    // document.exitFullscreen?.();
  }

  // 组件销毁/退出全屏时移除事件监听,避免内存泄漏
  ngOnDestroy() {
    document.addEventListener('fullscreenchange', () => {
      if (!document.fullscreenElement) {
        this.fullscreenContainer.nativeElement?.removeEventListener('keydown', this.handleEscPress, true);
      }
    }, { once: true });
  }
}

2. 兼容性替代方案

如果遇到部分浏览器对全屏下按键事件的拦截逻辑不同,可以选择拦截默认esc退出行为,自行控制退出时机:

  • 给全屏元素绑定keydown事件后,触发esc时先调用e.preventDefault()阻止浏览器默认退出行为
  • 等你的自定义操作全部执行完成后,再手动调用document.exitFullscreen()完成退出,可100%保证操作在退出前执行完成

内容的提问来源于stack exchange,提问作者kenneth-rebello

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:36:04