javascript - jQuery 动画不能正常工作

标签 javascript jquery css animation

我用 jquery 制作了一个简单的动画,但它并不总是有效。特别是:

$(".small-header").animate({top: "0"}, 500);

转换速度比预期的要快。看起来动画只适用于第一次。我不知道为什么。

$(document).ready(function( $ ){
    $(document).scroll(function(){
        var top = $(document).scrollTop();
        console.log(top);
        if (top > 160) 
        {
            $(".small-header").css("display", "block");
            $(".small-header").animate({top: "0"}, 500);
            $(".big-header").css("display", "none");
        }
        if (top < 160)
        {
            $(".small-header").css("top", "-5em");
            $(".small-header").css("display", "none");
            $(".big-header").css("display", "block");
        }
    });
});
body
{
  height: 1000px;
}
.big-header
{
    width: 100%;
    min-height: 10em;
    background-color: #ffffff;
    border-bottom: solid #aaaaaa 1px;
}
.small-header
{
    width: 100%;
    height: 4em;
    background-color: #ffffff;
    border-bottom: solid #aaaaaa 1px;
    position: fixed;
    top: -5em;
    left: 0;
    z-index: 9999; 
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="big-header">
</div>
<div class="small-header">
</div>

jsfiddle

最佳答案

试试这段代码:

$('el').animate({left: "+=100px"}, 500);
alert('Debug!');

您会看到警报出现在动画结束之前,因为动画是异步执行的。
这意味着元素首先移动 1px(例如),然后动画停止。其余代码开始执行,几毫秒后,对象又向右移动了一个像素。又过了几毫秒。
所以实际上动画在其余代码执行后继续。

您需要告诉 jQuery 您希望在动画结束后执行一个函数。将此函数作为第三个参数传递给 .animate() 方法:

$(".small-header").animate({top: "0"}, 500
// now the third parameter:
function () {
    $(".big-header").css("display", "none");
});

您需要了解动画不是内置在 javascript 中的。 jQuery 只是让制作它们变得更容易,在这里阅读幕后的内容 - How do js animations work?

关于javascript - jQuery 动画不能正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31325682/

相关文章:

javascript - Facebook Messenger 聊天机器人显示 "Check your connection and try again."

javascript - jquery 中的注释 更多 jquery 中的注释

javascript - 如何让 div/table 改变它们的大小?

css - 在 TD 内垂直对齐 Span

javascript - 弹出窗口内的关闭按钮不响应(点击事件上的 jQuery)

javascript - 如何将innerHTML添加到现有属性

javascript - 如何从 dataTransfer 获取对象数据?

javascript - 如何在 Dimple 中的不同绘图之间获得相同的类别颜色

jquery - 当 jQuery.post() 请求时,Django View 不会重定向

javascript - 使用 form-repeater 在填充的表中附加新行需要花费大量时间(10-15 秒) - jQuery