jQuery动画无法正常工作

时间:2015-07-09 18:40:11

标签: 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

1 个答案:

答案 0 :(得分:0)

试试这段代码:

$('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?

相关问题