全屏和退出全屏功能的实现

1. 判断状态

  // 浏览器前缀
  const [prefixName, setPrefixName] = useState('')
  // 浏览器是否支持全屏 默认支持
  const [isFullscreenData, setIsFullscreenData] = useState(true)
  // 是否全屏
  const [isFullscreen, setIsFullscreen] = useState(false)
   
  const screenRef = useRef(null)

 

2. 判断浏览器是否支持全屏

  // 判断是否支持全屏
  const canFullscreen = () => {
    let fullscreenEnabled = false
    // 判断浏览器前缀
    if (document.fullscreenEnabled) {
      fullscreenEnabled = document.fullscreenEnabled
    } else if (document.webkitFullscreenEnabled) {
      fullscreenEnabled = document.webkitFullscreenEnabled
      setPrefixName('webkit')
    } else if (document.mozFullScreenEnabled) {
      fullscreenEnabled = document.mozFullScreenEnabled
      setPrefixName('moz')
    } else if (document.msFullscreenEnabled) {
      fullscreenEnabled = document.msFullscreenEnabled
      setPrefixName('ms')
    }
    if (!fullscreenEnabled) {
      setIsFullscreenData(false)
    }
  }

3. 需要操作全屏的元素

  const screenRef = useRef(null)

  <div  ref={screenRef}>
        <a onClick={() => setFullScreen()}>
          {!isFullscreen ? '全屏' : '返回'}
        </a>
  </div>

 

4. 指定元素全屏

  

  // 全屏
  /**
  * @param {String} dom 要全屏的dom
  */
  const domFullscreen = dom => {
    const methodName = prefixName === '' ? 'requestFullscreen' : `${prefixName}RequestFullScreen`
    dom[methodName]()
  }

  // 退出全屏
  const exitFullscreen = () => {
    const methodName = prefixName === ''
      ? 'exitFullscreen'
      : `${prefixName}ExitFullscreen`
    document[methodName]()
  }

  // 全屏和返回的操作
  const setFullScreen = () => {
    if (isFullscreenData) {
      if (isFullscreen) {
        exitFullscreen()
        setIsFullscreen(false)
      } else {
        setIsFullscreen(!isFullscreen)
        domFullscreen(screenRef.current)
      }
    } else {
      message.info('该浏览器不支持全屏模式')
    }
  }

 

posted @ 2022-03-28 11:02  VictoriaC~  阅读(443)  评论(0编辑  收藏  举报