在 Reactjs 中滚动播放/暂停视频

我正在尝试实现一种功能,如果视频正在播放,则在滚动时暂停,反之亦然。目前我可以使用设置状态 true/false 的 onClick 函数来完成。但问题是视频在向下滚动后继续播放,直到我不再点击它暂停。我想保留 onClick 功能,同时还想添加 onScroll 功能。尝试这样做onScroll但没有工作。


const [playing, setPlaying] = useState(false);

  const videoRef = useRef(null);


  const handleVideoPress = () => {

    if (playing) {

      videoRef.current.pause();

      setPlaying(false);

    } else {

      videoRef.current.play();

      setPlaying(true);

    }

  };

  return (

    <div className="video">

      <video

        onClick={handleVideoPress}

        className="video__player"

        loop

        ref={videoRef}

        src={url}

      ></video>

    );

}


斯蒂芬大帝
浏览 183回答 1
1回答

慕田峪9158850

因此,这将阻止您的视频在任何滚动事件中播放。如果你希望它在离开视口时停止播放,你可以考虑使用类似IntersectionObserver API 的东西来做一些事情,如果它在视口中(播放视频)或在视口外(停止视频)。注意:大多数现代浏览器不允许 Javascript 启动视频,除非至少已经有一些用户与页面进行了交互。&nbsp;const [playing, setPlaying] = useState(false);&nbsp; const videoRef = useRef(null);&nbsp; useEffect(() => {&nbsp; &nbsp; window.addEventListener('scroll', debounce(handleScroll, 200))&nbsp; &nbsp; return () => {&nbsp; &nbsp; &nbsp; window.removeEventListener('scroll', handleScroll);&nbsp; &nbsp; };&nbsp; }, []}&nbsp; const startVideo = () => {&nbsp; &nbsp; videoRef.current.pause();&nbsp; &nbsp; setPlaying(false);&nbsp; }&nbsp; const pauseVideo = () => {&nbsp; &nbsp; videoRef.current.play();&nbsp; &nbsp; setPlaying(true);&nbsp; }&nbsp; const handleScroll = (e) => {&nbsp; &nbsp; if (playing) {&nbsp; &nbsp; &nbsp; pauseVideo();&nbsp; &nbsp; }&nbsp; }&nbsp; const handleVideoPress = () => {&nbsp; &nbsp; if (playing) {&nbsp; &nbsp; &nbsp; startVideo();&nbsp; &nbsp; } else {&nbsp; &nbsp; &nbsp; pauseVideo();&nbsp; &nbsp; }&nbsp; };&nbsp; return (&nbsp; &nbsp; <div className="video">&nbsp; &nbsp; &nbsp; <video&nbsp; &nbsp; &nbsp; &nbsp; onClick={handleVideoPress}&nbsp; &nbsp; &nbsp; &nbsp; className="video__player"&nbsp; &nbsp; &nbsp; &nbsp; loop&nbsp; &nbsp; &nbsp; &nbsp; ref={videoRef}&nbsp; &nbsp; &nbsp; &nbsp; src={url}&nbsp; &nbsp; &nbsp; ></video>&nbsp; &nbsp; );}我做了一个使用 React 的引用钩子的工作示例IntersectionObserver,可以在这里找到:https://codesandbox.io/s/strange-smoke-p9hmx如果您还有其他问题,请告诉我。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript