javascript 我如何检查退出全屏与nextjs?

vmpqdwk3  于 2023-09-29  发布在  Java
关注(0)|答案(2)|浏览(114)
'use client'

const  App = () => {
  const [isFScreen, setIsFScreen] = useState(false)

  useEffect(() => {
    const down = (e: KeyboardEvent) => {
        if (e.key === "Escape"){
          setIsFScreen(false)
        }
    }

    document.addEventListener("keydown", down)
  }, [])

  return(
    <div id="gameScreen">
     <span onClick={() => {
       setIsFScreen(!isFScreen)
       document.getElementById("gameScreen")?.requestFullscreen()}}>
         Full Screen
     </span>
    </div>
)}

当我按下ESC键一次时,它退出全屏,但“setIsFScreen”不会变为false。我得按两次才能让它变假。我该怎么解决这个问题?
我期待的状态是假的,当它退出全屏。

8hhllhi2

8hhllhi21#

只是使用监听事件全屏

const  App = () => {
  const [isFScreen, setIsFScreen] = useState(false)

  useEffect(() => {
    const exitHandler= (e:any) => {
       setIsFScreen(false);
    }

    document.addEventListener('fullscreenchange', exitHandler, false);
    document.addEventListener('mozfullscreenchange', exitHandler, false);
    document.addEventListener('MSFullscreenChange', exitHandler, false);
    document.addEventListener('webkitfullscreenchange', exitHandler, false);
  }, [])

  return(
    <div id="gameScreen">
     <span onClick={() => {
       setIsFScreen(!isFScreen)
       document.getElementById("gameScreen")?.requestFullscreen()}}>
         Full Screen
     </span>
    </div>
)}

支持Opera,Safari,Chrome与webkit,Firefox/Gecko与moz,IE 11与MSFullScreenChange,并将支持实际规范与fullscreenchange一旦它在所有浏览器中成功实现。显然,Fullscreen API只在现代浏览器中支持,所以我没有为旧版本的IE提供attachEvent回退。

a7qyws3x

a7qyws3x2#

const [isFScreen, setFullScreen] = useState(false);

  useEffect(() => {
    function handleFullScreenChange() {
      if (document.fullscreenElement) {
        setFullScreen(true);
      } else {
        setFullScreen(false);
      }
    }

    document.addEventListener('fullscreenchange', handleFullScreenChange);

    return () => {
      document.removeEventListener('fullscreenchange', handleFullScreenChange);
    };
  }, []);

  useEffect(() => {
    function handleEscKeyPress(event:any) {
      if (event.key === 'Escape') {
        exitFullScreen();
      }
    }

    if (isFScreen) {
      window.addEventListener('keydown', handleEscKeyPress);
    } else {
      window.removeEventListener('keydown', handleEscKeyPress);
    }

    return () => {
      window.removeEventListener('keydown', handleEscKeyPress);
    };
  }, [isFScreen]);

  const enterFullScreen = () => {
    if (document.getElementById("gameScreen")?.requestFullscreen) {
      document.getElementById("gameScreen")?.requestFullscreen();
    }
  };

  const exitFullScreen = () => {
    if (document.exitFullscreen) {
      document.exitFullscreen();
    }
  };

我用ChatGPT解决了这个问题。谢谢聊天!

相关问题