为什么 Jquery animate() 在我的案例中不起作用?

Why is Jquery animate() not working in my case?

我有以下 HTML 布局:

<html>
    <head>
        ...
    </head>
    <body>
        <header class="fluid-container">
            <div class="nav-wrapper">
                ...
            </div>
        </header>
        <section class="salutation fluid-container">
            <div class="intro-wrapper">
                ...
            </div>
        </section>
    </body>
</html>

我的 objective 是在我的 window 滚动超过 60px 时隐藏 intro-wrapper,反之亦然。因此,我实现了以下 Jquery 代码来实现上述目标。

var checkScroll = true;

$(window).scroll(function() {

    if($(this).scrollTop() > 60 && checkScroll) {
        $(".intro-wrapper").stop().animate({display:'none'}, 400);
        checkScroll = false;
        console.log('Scrolling down. \t checkScroll: ' + checkScroll);
    } 

    else if($(this).scrollTop() < 60 && !checkScroll) {
        $(".intro-wrapper").stop().animate({display:'block'}, 400);
        checkScroll = true;
        console.log('Scrolling up. \t\t checkScroll: ' + checkScroll);
    }
});

但不幸的是,我一直无法理解为什么没有出现动画。请指出我上面代码中的错误并帮助我找出解决方案。

请注意,console.log() 正在按预期呈现结果,即,条件得到适当满足,循环适当地完成它的旅程。

在这里您可以使用 jquery .fadeIn() .fadeOut() 方法来延迟显示或隐藏元素,而不是动画。

显示 属性 无法在 jQuery 动画中使用。 参考 animate

display will/does 不适用于 animate。除了其他答案之外,您还可以使用 show()hide()

来自http://api.jquery.com/animate/

注意:与 shorthand 动画方法(例如 .slideDown() 和 .fadeIn())不同,.animate() 方法不会使隐藏的元素作为效果的一部分可见。例如,给定 $( "someElement" ).hide().animate({height: "20px"}, 500),动画将 运行,但元素将保持隐藏状态。

显示到 none/block 无法设置动画。尝试使用 overflow: hidden

将高度动画化为 0

或者您可以使用 css 轻松转换:

// hide it
$(".intro-wrapper").addClass('hidescroll');
// show it again
$(".intro-wrapper").removeClass('hidescroll');

然后在css:

.intro-wrapper {
    transition: height .5s ease-in;
    height: 400px;
}

.intro-wrapper.hidescroll {
    height: 0;
    overflow: hidden;
}