需求背景:移动端打开网站,发现不能充分利用屏幕空间,浏览器自带的全屏功能很难找,用户体验较差。并且有些元素比如图片需要去放大看,这时如果点击就能全屏,再点击就退出,用户体验可以提升。

Step1:安装第三方插件screenfull

Npm官方地址:https://www.npmjs.com/package/screenfull

执行命令安装依赖:

npm install screenfull save

step2:vue中引入使用

screenfull.isFullscreen:检测是否全屏

screenfull.isEnabled:检测是否支持全屏

screenfull.request():进入全屏

screenfull.exit():退出全屏,注意是退回到进入全屏的状态

screenfull.toggle():切换全屏,较常用

<div class="search__screen" @click="handleFullScreen">
        <span class="iconfont icon-fullscreen-exit" v-if="isFullScreenTag"></span>
        <span class="iconfont icon-fullscreen" v-else></span>
 </div>
import screenfull from 'screenfull'

    const handleFullScreen = () => {
      // 检测当前是否全屏,如果是全屏就退出,否则就全屏
      console.log(screenfull.isFullscreen)
      if (screenfull.isFullscreen) {
        isFullScreenTag.value = false
        screenfull.toggle()
        // screenfull.exit()
      } else {
        // 进入全屏
        isFullScreenTag.value = true
        screenfull.toggle()
        // screenfull.request()
      }
     }

Step3:封装成工具

给其它组件用、精简setup

// 封装:切换全屏
const useScreenfullEffect = () => {
  const isFullScreenTag = ref(false)
  const handleFullScreen = () => {
    if (screenfull.isEnabled) {
      // 检测当前是否全屏,如果是全屏就退出,否则就全屏
      if (screenfull.isFullscreen) {
        screenfull.toggle()
        isFullScreenTag.value = false
        // screenfull.exit()
      } else {
        // 进入全屏
        screenfull.toggle()
        isFullScreenTag.value = true
        // screenfull.request()
      }
    } else {
      alert('提示:不支持切换全屏。')
    }
  }
  return { isFullScreenTag, handleFullScreen }
}

Step4:升级工具:全屏展示dom节点

用screenfull.toggle(element),可以来回切换,不用判断是否全屏

思考:页面是否也可以不用判断?

Div中传递当前点击的dom节点

<div class="search__body" @click="handleFullscreenElement($event.target)">

// 封装:整个页面、元素切换全屏
const useScreenfullEffect = () => {
  const isFullScreenTag = ref(false)
  // 检测当前页面是否全屏,如果是全屏就退出,否则就全屏
  const handleFullScreen = () => {
    if (screenfull.isEnabled) {
      if (screenfull.isFullscreen) {
        screenfull.toggle()
        isFullScreenTag.value = false
        // screenfull.exit()
      } else {
        // 进入全屏
        screenfull.toggle()
        isFullScreenTag.value = true
        // screenfull.request()
      }
    } else {
      alert('提示:不支持切换全屏。')
    }
  }
  // 点击当前元素进入全屏,一般为图片
  const handleFullscreenElement = (element) => {
    if (screenfull.isEnabled) {
      screenfull.toggle(element)
    } else {
      alert('提示:不支持切换全屏。')
    }
  }
  return { isFullScreenTag, handleFullScreen, handleFullscreenElement }
}

Logo

前往低代码交流专区

更多推荐