在React.js中播放/暂停视频onScroll

时间:2020-09-14 19:02:08

标签: javascript reactjs scroll

我正在尝试实现一种功能,在播放视频时,如果正在播放,则在滚动时会暂停,反之亦然。目前,我可以使用将状态设置为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>
    );
}

1 个答案:

答案 0 :(得分:0)

因此,这将阻止您的视频在任何滚动事件下播放。如果您想让它在离开视口后停止播放,可以考虑使用IntersectionObserver API之类的方法来进行操作(如果它在视口中(播放视频)或在视口之外(停止视频))

注意:大多数现代浏览器不允许Javascript播放视频,除非已经与该页面至少有一些用户交互。

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

  useEffect(() => {
    window.addEventListener('scroll', debounce(handleScroll, 200))

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []}

  const startVideo = () => {
    videoRef.current.pause();
    setPlaying(false);
  }

  const pauseVideo = () => {
    videoRef.current.play();
    setPlaying(true);
  }

  const handleScroll = (e) => {
    if (playing) {
      pauseVideo();
    }
  }

  const handleVideoPress = () => {
    if (playing) {
      startVideo();
    } else {
      pauseVideo();
    }
  };

  return (
    <div className="video">
      <video
        onClick={handleVideoPress}
        className="video__player"
        loop
        ref={videoRef}
        src={url}
      ></video>
    );
}

我举了一个使用IntersectionObserver和React的ref钩子的工作示例,可以在这里找到

https://codesandbox.io/s/strange-smoke-p9hmx

如果您还有其他问题,请告诉我。