全屏和退出全屏功能的實現
阿新 • • 發佈:2022-03-28
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('該瀏覽器不支援全屏模式') } }