JS web页面实现全屏/退出全屏

技术栈:Vue3 + TypeScript + Ant Design Vue4

简介

部分项目在开发过程中,会有全屏功能的需求,实现指定元素全屏显示,比如数据大屏等。
于是,本篇来通过调用浏览器原生API实现此功能组件。

全屏组件

Vue 布局

需要全屏显示的Element id由外部动态传入,自定义。
增加两个icon对应进入全屏、退出全屏的操作入口,绝对定位。

<template>
  <div :id="eleId" class="fullScreenContainer">
    <FullscreenOutlined v-if="!isFull" @click="handleFull" class="fullScreenIcon" />
    <FullscreenExitOutlined v-else @click="existFull" class="fullScreenIcon" />
    <slot></slot>
  </div>
</template>
<style lang="scss" scoped>
.fullScreenContainer {
  position: relative;
}
.fullScreenIcon {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 30px;
  color: gray;
}
</style>

TS逻辑

流程为进入页面,元素本为非全屏模式,监听页面全屏状态。
点击全屏icon,判断浏览器是否支持全屏且目标元素存在且浏览器全屏事件存在,条件成立,调用浏览器接口。
点击退出全屏icon,判断浏览器是否支持全屏且全屏元素存在且浏览器退出全屏事件存在,条件成立,调用浏览器接口。
维护 isFull 字段,控制全屏icon的显示。

import { defineComponent, ref } from 'vue'
import { FullscreenOutlined, FullscreenExitOutlined } from '@ant-design/icons-vue'

export default defineComponent({
  name: 'FullScreen',
  props: {
    id: {
      type: String // elementId
    }
  },
  components: {
    FullscreenOutlined,
    FullscreenExitOutlined
  },
  setup(props) {
    const eleId = ref(props.id)
    const isFull = ref(false)

    // 检查是否支持全屏
    const checkIsFull = () => {
      return document.fullscreenEnabled
    }

    // 进入全屏
    const handleFull = () => {
      const element: HTMLElement | null = document.getElementById('fullScreenElement')
      if (checkIsFull() && element && element.requestFullscreen) {
        element.requestFullscreen().then(() => {
          isFull.value = true
        })
      }
    }

    // 退出全屏
    const existFull = () => {
      const fullscreenElement = document.fullscreenElement
      if (checkIsFull() && fullscreenElement && document.exitFullscreen) {
        document.exitFullscreen().then(() => {
          isFull.value = false
        })
      }
    }

    // 是否全屏状态变更时
    const handleFullscreenChange = () => {
      if (document.fullscreenElement) {
        isFull.value = true
        console.log('进入全屏模式')
      } else {
        isFull.value = false
        console.log('退出全屏模式')
      }
    }
    // 监听全屏状态
    document.addEventListener('fullscreenchange', handleFullscreenChange)

    return {
      eleId,
      isFull,
      handleFull,
      existFull
    }
  }
})

应用

组件使用

在需要的文件内部引入全屏组件并调用。
组件应用

效果

非全屏模式

非全屏模式

全屏模式

全屏模式

参考资料

关于浏览器API调用说明可参考一下文档。
MDN浏览器全屏API:https://developer.mozilla.org/en-US/docs/Web/API/Fullscreen_API
其他博客:https://cloud.tencent.com/developer/article/2329582

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值