我正在使用此脚本为锚点内的一些图像设置动画:
$('#locations a').each(function() {
// set opacity 0 take initial position
$(this).css('opacity', '0');
var left = $(this).css('left');
var top = $(this).css('top');
// reset position and animate
$(this).css({'left' : '0', 'top' : '0'});
$(this).animate({left: left, top: top, opacity: 1});
});
我需要使用jquery each()函数来获取初始位置。 但是,我想按顺序为返回的元素设置动画。这可能吗?
答案 0 :(得分:1)
你可以用一种不那么复杂的方式做到这一点,比如:
$('#locations a').each(function(i) {
var left = $(this).css('left'),
top = $(this).css('top');
$(this).css({opacity: 0, left: 0, top: 0})
.delay(400 * i)
.animate({left: left, top: top, opacity: 1});
});
You can test it here。它主要是简化,唯一重要的补充是.delay(400 * i)
和i
到function(i) {
。
这只是使用提供的i
作为.each()
回调的第一个参数,并将.delay()
(在此元素上开始动画之前的延迟)相乘每个元素的数量。 400
default duration .animate()
为400毫秒。所以第一个元素立即开始,下一个元素在400毫秒开始,下一个元素在800毫秒开始,依此类推...当它之前的动画应该完成时。
你当然可以制作一个自定义队列等......但这看起来有点简单:)
编辑:,因为您对构建队列感兴趣,它看起来像这样:
$('#locations a').each(function(i) {
var left = $(this).css('left'),
top = $(this).css('top'),
a = $(this).css({opacity: 0, left: 0, top: 0});
$(document).queue('myQueue', function(n) {
a.animate({left: left, top: top, opacity: 1}, n);
});
});
$(document).dequeue('myQueue');
You can test it here,我们正在使用.queue()
对document
上的自定义队列中的功能进行排队,然后使用.dequeue()
将其踢出。 n
是队列中的下一个函数,我们在.animate()
完成后通过提供它作为要运行的回调函数来调用。
答案 1 :(得分:0)
您可以在jQuery中设置自己的自定义队列。
根据您的评论举例
我创建了一个名为“MyCustomQueue”的自定义队列,我随意将它放在body标签上。我使用JavaScript闭包通过设置名为“this $”的变量来为队列的每个函数中的特定元素设置动画。
<!DOCTYPE html>
<html lang="en">
<head>
<title>Queues Me</title>
<style>
a {
position:relative;
top:0;
left:0;
}
</style>
<script type="text/javascript" src="http://ajax.microsoft.com/ajax/jquery/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function () {
$('#locations a').each(function () {
var this$ = $(this);
// set opacity 0 and take initial position
this$.css('opacity', '0');
var left = this$.css('left');
var top = this$.css('top');
// reset position and populate the queue with animations
this$.css({ 'left': '420px', 'top': '1820px' });
$('body').queue("MyCustomQueue", function () {
this$.animate({ left: left, top: top, opacity: 1 }, 500, function () {
$('body').dequeue("MyCustomQueue");
});
});
});
$('body').dequeue("MyCustomQueue");
});
</script>
</head>
<body>
<div>
<div id="locations">
<ul>
<li><a href="#">Foo</a></li>
<li><a href="#">Moo</a></li>
<li><a href="#">Poo</a></li>
<li><a href="#">Woo</a></li>
<li><a href="#">Zoo</a></li>
</ul>
</div>
</div>
</body>
</html>