随机放置渐变和淡出的div



我一直在寻找并试图解决这个问题一段时间了,我不知道。

这是我的react函数。

粗体的代码是正在讨论的函数,现在它是如何工作的,是该函数迭代视频数组,然后随机定位这些元素,在不同的时间,由于setInterval。

export default function RandomVideos(){
useEffect(() => {
const videos = Array.from(document.getElementsByClassName('video_container') as HTMLCollectionOf<HTMLElement>);
const Width = (document.getElementById('container') as HTMLElement).offsetWidth;
const Height = (document.getElementById('container') as HTMLElement).offsetHeight;
function fadeIn(thisVideo: HTMLElement){
thisVideo.classList.add('fade-in');
thisVideo.classList.remove('fade-out');  
}
function fadeOut(thisVideo: HTMLElement){
thisVideo.classList.add('fade-out');
thisVideo.classList.remove('fade-in');  
}
function randomlyPlaced(){
videos.forEach(thisVideo =>  {
setInterval(function() {
thisVideo.classList.add("fade-in");
const randomTop = Math.round(Math.random() * Height) - 20;
const randomLeft = Math.round(Math.random() * Width) - 20;
thisVideo.style.top = randomTop +"px";
thisVideo.style.left = randomLeft +"px";
fadeIn(thisVideo)
}, (Math.floor(Math.random() * 7000) + 2000))
})
}
randomlyPlaced()

});
return(
<div className="container" id="container">
{RandomVideosProps.map((video) => (
<div className="video_container" key={video.id}>
<video src={video.src}></video>
{video.text}
</div>
))}
</div>
);}

代码按预期工作,视频元素的第一次迭代淡出,然后每个间隔随机定位自己。但是我想让元素在每个间隔上淡出,然后再淡入。我不知道如何做到这一点,因为间隔是在forEach方法内。

在forEach方法之外的间隔意味着数组元素将随机地同时定位。这正是我想要避免的。

那么我希望这段代码如何工作-每个数组元素在一个随机位置fadesIn,然后在另一个随机位置fadesOut和fadesIn。

我希望得到任何建议或帮助,我也尽量避免使用jQuery,因为我知道它通常不会在react中使用。

我没有尝试使用任何库。

我正在写一个typescript react文件。

谢谢!

我设法解决这个使用setTimout在我的setInterVal -我觉得我已经解决了这个有点hackily,但它的工作-

我还是想知道人们是否认为这是一个好的解决方案,或者是否有更好的方法。

function randomlyPlaced(){
videos.forEach(thisVideo =>  {
setInterval(function() {
setTimeout(function() {
thisVideo.classList.add("fade-in");
const randomTop = Math.round(Math.random() * Height) - 20;
const randomLeft = Math.round(Math.random() * Width) - 20;
thisVideo.style.top = randomTop +"px";
thisVideo.style.left = randomLeft +"px";
fadeIn(thisVideo)
}, 5000)
fadeOut(thisVideo)
}, (Math.floor(Math.random() * 12000) + 6000))
})
}
randomlyPlaced()

最新更新