我有一个应用程序 - 视频编辑器。我将视频加载到其中(时间线)并按播放。视频开始播放,跟踪器沿着包含视频的容器爬行。当跟踪器到达屏幕末端时,视频容器应向左移动,以便跟踪器不会从视图中消失。
const { currentPosition, setCurrentPosition } = useContext(EditorContext);
const scrollContainerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const scrollContainer = scrollContainerRef.current;
if (!scrollContainer) return;
if (scrollContainer) {
const rect = scrollContainer.getBoundingClientRect();
const rightLimit = rect.width - 200;
if (currentPosition > rightLimit) {
scrollContainer.scrollBy({ left: 100, behavior: 'smooth' });
}
}
}, [currentPosition]);
Currently the container only moves to the left when I pause the video and the tracker stops.
试试这个代码;
const { currentPosition, setCurrentPosition } = useContext(EditorContext);
const scrollContainerRef = useRef<HTMLDivElement | null>(null);
useEffect(() => {
const scrollContainer = scrollContainerRef.current;
if (!scrollContainer) return;
const handleScroll = () => {
const scrollLeft = scrollContainer.scrollLeft;
const scrollWidth = scrollContainer.scrollWidth;
const containerWidth = scrollContainer.clientWidth;
// Calculate the right edge of the visible area
const rightLimit = scrollWidth - containerWidth;
// Check if tracker is close to the right edge
if (currentPosition > rightLimit - 100) {
// Scroll by a fixed amount with smooth behavior
scrollContainer.scrollBy({ left: 100, behavior: 'smooth' });
}
};
// Attach scroll event listener to the container
scrollContainer.addEventListener('scroll', handleScroll);
// Clean up function to remove event listener on unmount
return () => scrollContainer?.removeEventListener('scroll', handleScroll);
}, [scrollContainerRef]); // Dependency on scrollContainerRef