我試圖在渲染時自動播放視頻,但只有一次。在懸停效果上,我希望它回圈播放視頻。我曾嘗試在 mouseOver 上使用 event.target.play() 但沒有成功。
任何幫助將不勝感激 :)
<video
className="videos"
autoPlay={true}
onm ouseOver={event => event.target.play()}
onm ouseOut={event => event.target.pause()}
muted={true}
src={prompt}>
</video>
uj5u.com熱心網友回復:
您可以使用 onEnded 事件和滑鼠懸停來回圈它。還使用 useRef 可以輕松設定/播放而不是從所有回呼傳遞事件。檢查下面的代碼,
import { useEffect, useRef, useState } from "react";
import testVideo from "./testVideo.mp4";
export default function App() {
const ref = useRef(null);
const [focus, setFocus] = useState(false);
const loop = () => {
ref.current.play();
};
const onEndedLoop = () => {
if (focus) loop(); // when ended check if its focused then loop
};
useEffect(() => {
if (focus) loop(); // when focused then loop
}, [focus]);
return (
<div className="App">
<h2>Loop video with hover ReactJS!</h2>
<video
id="video"
ref={ref}
style={{ width: "300px" }}
autoPlay
onMouseOver={() => setFocus(true)}
onm ouseOut={() => setFocus(false)}
muted={true}
src={testVideo}
onEnded={onEndedLoop}
></video>
</div>
);
}
檢查作業演示 - https://codesandbox.io/s/loop-video-on-hover-qegu7
uj5u.com熱心網友回復:
@Madhuri 有很好的答案。但是,如果我們添加一個在未聚焦時暫停回圈的功能,則只會在聚焦時回圈視頻,并在未懸停或未聚焦時停止。
const loop = () => {
ref.current.play();
};
const pauseLoop = () => {
ref.current.pause();
};
const onEndedLoop = () => {
if (focus) loop(); // when ended check if its focused then loop
};
useEffect(() => {
if (focus) loop(); // when focused then loop
if (!focus) pauseLoop(); // when not focused then pause loop
}, [focus]);
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/339349.html
標籤:javascript html 反应 jsx
