JS全屏切换功能

2024-02-27  本文已影响0人  小石头糖糖
// icon 定义
const [fullScreenIcon, setFullScreenIcon] = useState('quanping');

// 切换 icon
  const toggleFullscreenIcon = () => {
    if (document.fullscreenElement) {
      setFullScreenIcon('tuichuquanping');
    } else {
      setFullScreenIcon('quanping');
    }
  };

// 切换功能
const fullScreen = () => {
  if (!document.fullscreenElement) {
    // 开启全屏
    const element = document.documentElement;
    // 兼容主流浏览器
    if (element.requestFullscreen) {
      element.requestFullscreen();
    } else if (element.mozRequestFullScreen) {
      element.mozRequestFullScreen();
    } else if (element.webkitRequestFullscreen) {
      element.webkitRequestFullscreen();
    } else if (element.msRequestFullscreen) {
      element.msRequestFullscreen();
    }
  } else {
    // 退出全屏
    document.exitFullscreen && document.exitFullscreen();
  }
};

// 监听全屏
  document.addEventListener('fullscreenchange', toggleFullscreenIcon);

// dom 应用
<Icon name={fullScreenIcon}  onClick={fullScreen} />

上一篇下一篇

猜你喜欢

热点阅读