首页 > 解决方案 > 淡入淡出动态 div

问题描述

几天来,我一直在为期末考试做一个学校项目,这件事发生了:我的 div(s) 不断淡入淡出,过了一会儿它们停止了,到目前为止我已经有了这个 jquery

在这里,我创建了一些变量,以使 div 在达到固定高度时消失(正如您在 css 中看到的那样,div 是粘性的,因此它不会在我想要的任何时候通过获取高度来工作)

$('.processor').each(function(){
$counter += 1;
fromTop[$counter] = $(this).offset().top;
});

$(window).scroll(function() {
$counter = 0;
$('.processor').each(function(){
    $counter += 1;
    if($(window).scrollTop() > fromTop[$counter])
    {
        $(this).fadeTo(500,0);   
    }
    else
    {
        $(this).fadeTo(500,1);
    }
    if($(window).scrollTop() > fromTop[$counter-1])  //Check if the scroll is enought to make the other div appear
    {
        $(this).fadeTo(500,1);
    }
 });
 });

--- CSS ---

.processor{
width:65%;
height:70%;
background: linear-gradient(rgba(179, 0, 0, 0.75), rgba(95, 0, 0, 0.75));;
margin: 0 auto;
overflow:hidden;
border-radius:3px;
top: 18%;
position:sticky;
margin-bottom:250px;
}

标签: jquerycss

解决方案


jQuery 会将动画添加到队列中,这会导致一段时间后播放多个动画(我记得不久前在多个带有 mouseOver 动画的网站上看到过这种情况)。

问题是您确实希望每次窗口滚动时都进行检查,但是当用户滚动时,该事件当然会被触发多次。如果您知道在 .scroll 函数中设置的动画是最终的,则可以将动画队列显式设置为 1,如下所示:

if ($(this).queue().length > 1) $(this).queue() = 1; //do this before applying fadeTo

这将允许队列完成其当前动画,然后运行您想要的动画,并在那里结束。所以滚动了一堆之后,div最多只会经过2个动画。


推荐阅读