解决vue3项目页面全屏后按esc退出全屏监听不到keydown事件

2024-01-07 23:04:05

1. 全屏、退出全屏功能代码

const handleScreen = (type: number) => {
  // 整个html全屏
  let eleDom = document.getElementById("large-screen") as any;
  let doc = document as any;
  if (type === 1) {
    isFullScreen.value = true;
    if (eleDom.RequestFullScreen) {
      eleDom.RequestFullScreen();
    }
    //兼容火狐
    if (eleDom.mozRequestFullScreen) {
      eleDom.mozRequestFullScreen();
    }
    if (eleDom.webkitRequestFullScreen) {
      console.log(eleDom.webkitRequestFullScreen);
      eleDom.webkitRequestFullScreen();
    }
    //兼容IE,只能写msRequestFullscreen
    if (eleDom.msRequestFullscreen) {
      eleDom.msRequestFullscreen();
    }
  } else {
    isFullScreen.value = false;
    if (doc.exitFullScreen) {
      doc.exitFullscreen();
    }
    //兼容火狐
    if (doc.mozCancelFullScreen) {
      doc.mozCancelFullScreen();
    }
    //兼容谷歌等
    if (doc.webkitExitFullscreen) {
      doc.webkitExitFullscreen();
    }
    //兼容IE
    if (doc.msExitFullscreen) {
      doc.msExitFullscreen();
    }
  }

  emit("fullScreen", isFullScreen.value);
};

2. 现象:点击handleScreen(type) 方法退出全屏,页面正常显示;但是按ESC退出全屏时,页面监听不到keydown事件,无法调用退出全屏方法handleScreen(type)

// 监听不到keydown
document.addEventListener("keydown", (e:any)=>{
	if (e.keyCode == 27) {
    console.log("Esc执行");
  }
})

3. 解决措施:通过resize这个原生监听视口宽度的方法 ,判断document是否全屏来完成

 
onMounted(() => {
  window.addEventListener("resize", listenEsc);
});
 
onUnmounted(() => {
  // 页面销毁的时候清除监听事件
  window.removeEventListener("resize", listenEsc);
});

const listenEsc = ()=>{
	if( !checkFull() ){
		// 退出全屏
		handleScreen(2)
	}
};

const checkFull = ()=>{
   //判断浏览器是否处于全屏状态 (需要考虑兼容问题)
   let ele = document as any;
   let isFull =
     //火狐浏览器
     ele .mozFullScreen ||
     ele .fullScreen ||
     //谷歌浏览器及Webkit内核浏览器
     ele .webkitIsFullScreen ||
     ele .webkitRequestFullScreen ||
     ele .mozRequestFullScreen ||
     ele .msFullscreenEnabled;
   if (isFull === undefined) {
     isFull = false;
   }
   return isFull;
};


文章来源:https://blog.csdn.net/csdn_cai_csdn/article/details/135379163
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。