Vue3 全屏模式展示元素及监听全屏状态事件

描述

举个🌰:这里有一个需求,点击开启大屏按钮,使展示数据的元素全屏展示,全屏中当然还有一个关闭全屏按钮,这两个操作就需要调用开启全屏和关闭全屏的方法。但是必须要考虑一点就是当用户按 Esc 键时,也应该将全屏关闭,这就需要对全屏状态进行监听了。

1、激活全屏模式

对于一个你想要以全屏模式的元素,可以通过调用它的 Element.requestFullscreen() 方法就能简单的激活它的全屏模式。

// index.vue
<div v-if="isShowScreen" id="screen"></div>
// 点击开启全屏按钮事件
const clickHandle = () => {
    isShowScreen.value = true;
    nextTick(() => {
      const elem = document.getElementById('screen') as HTMLElement;
      if (elem.requestFullscreen) {
        elem.requestFullscreen();
      }
    });
  };

2、关闭全屏模式

首先先来说说,通过我们编程方式调用 Document.exitFullscreen(),就是例子中说到的点击关闭按钮。

const offHandle = () => {
    if (document.fullscreenElement) {
      document.exitFullscreen();
    }
  };

3、监听全屏事件

用户总是可以自行退出全屏模式的:按下 Esc 键,这时候我们就可以监听全屏的状态来做一些需求需要的操作

const checkFull =() => {
    let isFull = document.fullscreenElement?true:false;
    if (isFull === undefined||isFull === null) isFull = false;
    return isFull;
  };

onMounted(() => {
    window.addEventListener('fullscreenchange', () => {
    // 监听到屏幕变化,在回调中判断是否已退出全屏
         if(!checkFull()) {
          isShowScreen.value = false;  // 隐藏了全屏的内容
          document.exitFullscreen();
      }
    });
  });

最后需要注意的一点是:
浏览器之间的差异性,比如 Gecko 自动为元素添加了 CSS 规则,使其拉伸以填满屏幕。WebKit 没有这样做,所以可以加入以下代码:

#myvideo:-webkit-full-screen {
  width: 100%;
  height: 100%;
}

还有更多的全屏 API 可以参考全屏指南

  • 3
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
你可以使用 Vue事件监听机制来监测全屏状态下的 ESC 键按下事件。首先,你需要在组件的 `mounted` 钩子函数中添加全屏状态的监测代码,然后在组件销毁时移除监听。 下面是一个示例: ```vue <template> <div> <!-- 组件内容 --> </div> </template> <script> export default { mounted() { // 监听全屏状态下的 ESC 键按下事件 document.addEventListener("fullscreenchange", this.handleEscKey); document.addEventListener("webkitfullscreenchange", this.handleEscKey); document.addEventListener("mozfullscreenchange", this.handleEscKey); document.addEventListener("MSFullscreenChange", this.handleEscKey); }, beforeDestroy() { // 移除监听 document.removeEventListener("fullscreenchange", this.handleEscKey); document.removeEventListener("webkitfullscreenchange", this.handleEscKey); document.removeEventListener("mozfullscreenchange", this.handleEscKey); document.removeEventListener("MSFullscreenChange", this.handleEscKey); }, methods: { handleEscKey(event) { // 判断是否为 ESC 键按下事件 if ( (event.key === "Escape" || event.keyCode === 27) && (document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement) ) { // 在这里处理 ESC 键按下事件 console.log("ESC 键按下"); } }, }, }; </script> ``` 在上面的示例中,我们通过监听 `fullscreenchange` 事件来检测全屏状态的改变,并在 `handleEscKey` 方法中判断是否为 ESC 键按下事件。如果是 ESC 键按下,并且当前处于全屏状态,你可以在该方法中进行相应的操作。 这样,当你的 Vue 组件处于全屏状态时,就能够监听到 ESC 键按下事件了。
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值