[英]jQuery animation doesn't work properly
我在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使得制作起來更容易,在這里了解幕后花絮-js動畫如何工作?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.