我用 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>
最佳答案
试试这段代码:
$('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/