Jquery滚动淡出

Jquery scroll fadeout

本文关键字:淡出 滚动 Jquery      更新时间:2023-09-26

我正在使用jQuery插件。当我向下滚动时,淡出效果是有效的,但当我滚动回顶部时,它不会再次显示我的div(#header)为了使div再次出现,我需要更改什么?

查询

$(window).scroll(function() {
    if ($('#header:above-the-top')) {
        $('#header').addClass('animated fadeOut');
        console.log('fadeOut');
    } else if ($('#header:above-the-top')) {
        $('#header').show();
        console.log('fadein');
    }
});

首先,我不明白为什么在相同条件下使用if-else-if语句。无论如何,我建议你给#header显示:none;使用css,然后使用JQuery管理fadeIn和Out。尝试以这种方式更改代码:

$(window).scroll(function() {
if ($('#header:above-the-top')) {
    $('#header').fadeOut(2000); //You can change the fadeOut parameter
    console.log('fadeOut');
} else if ($('#header:above-the-top')) {
    $('#header').fadeIn(2000);
    console.log('fadein');
}
});

或者,如果您喜欢在没有动画的情况下显示和隐藏div,则可以使用显示和隐藏方法。

$(window).scroll(function() {
if ($('#header:above-the-top')) {
    $('#header').hide(); //You can change the fadeOut parameter
    console.log('fadeOut');
} else if ($('#header:above-the-top')) {
    $('#header').show();
    console.log('fadein');
}

或者至少如果你想使用这个类,你必须移除和添加这个类才能使它动画化。记住hasClass()和removeClass()这两个方法。

好吧,您总共提供了3个代码。一个在问题上,另一个在评论上,最后一个在制作网站上。有了这些和之前的评论,我想我知道你想做什么。

在这个答案中,我放弃了对Viewport selections for jQuery插件的依赖,转而使用purejQuery。我放弃了这种依赖关系,因为它没有像您预期的那样工作,只会增加所需逻辑的复杂性。

我们需要的是一个用于滚动的事件处理程序,它将节点设置为在特定点后向下滚动时fadeOut,以及在达到特定点后向上滚动

使用注释中提供的代码,您几乎完全理解了特定点的部分,但您忘记了(或没有意识到)核心部分:检测何时向下滚动,何时向上滚动

所以,这是代码:

var scrollTopStartFadeOut = 300; // In wich scroll position we are going to start fade Out
var scrollTopStartFadeIn = 720; // In wich scroll position we are going to start fade Out
var lastScrollTop = 0; //We set a variable to store the last scroll top
$(window).scroll( function(){
    var actualScrollTop = $(this).scrollTop(); 
    if (actualScrollTop >= lastScrollTop && actualScrollTop > scrollTopStartFadeOut){ // Is scrolldown and scrolltop is after the scrolltop for fadeout? Then, we fade out!
        $('#header').removeClass('fadeInUp').addClass('animated fadeOut');
        console.log('fadeOut');
    } 
    else if (actualScrollTop < lastScrollTop && actualScrollTop < scrollTopStartFadeIn){ // Is scrollup and scrolltop is before the scrolltop for fadein? Then, we fade in!
        $('#header').removeClass('fadeOut').addClass('animated fadeInUp');
        console.log('fadeInUp');
    }
    lastScrollTop = $(this).scrollTop(); // Updates the lastScrollTop
});

为了检测(好吧,基本检测)何时向下滚动,何时向上滚动,我们设置了一个名为lastScrollTop的变量,用于存储最后一个scrollTop值。有了这个值,我们可以将其与实际的scrolltop进行比较,然后知道何时上升(如果最后一个大于实际值),何时下降(如果最后最后一个低于实际值)。

此外,我设置了两个变量来更改scrollTop值,使fadeOutfadeIn。我认为答案上的值与制作网站上的预期效果相匹配。

最后,还有另一个细节可以让它发挥作用,在

添加新的类之前,我们需要删除oposite效应的类。

我希望你能理解一切,但如果有什么解释不好或什么的,请告诉我们!

我制作了一个工作jsFiddle来显示效果: