2011-03-02 59 views
0

我有一个滑块,点击后,垂直动画一个div,然后返回到与启动时相同的位置。jquery动画n次?

http://www.eirestudio.net/hosting-files/markup/

我的问题是;我怎么能让这个滑块滑动n次,让我们说10而不是一次?

的JavaScript

$('#featured li.block div').click(function() 
{ 
    $(this).animate 
    ({ 
     top: "-=200" 
    }, 300, function() 
    { 
     $(this).css('top', '220px').animate 
     ({ 
      top: "-=220" 
     }, 300); 
    }); 
}); 

HTML

<div id="featured"> 
    <div class="wrapper"> 
     <ul> 
      <li class="block"> 
       <div>aaa</div> 
      </li> 
      <li class="block"> 
       aaa 
      </li> 
      <li class="block"> 
       aaa 
      </li> 
      <li class="block"> 
       aaa 
      </li> 
      <li class="block"> 
       aaa 
      </li> 
     </ul> 
    </div> 
</div> 

回答

3

你可以声明回调需要自己来处理动画的循环点击事件里面的函数。

$('#featured li.block div').click(function() { 
    var f = function($this, count) { 
     $this.animate({ 
      top: "-=200" 
     }, 300, function() { 
      $this.css('top', '220px').animate({ 
       top: "-=220" 
      }, 300, function() { 
       if (count > 0) { 
        count = count - 1; 
        f($this, count); 
       } 
      }); 
     }); 
    }; 
    f($(this), 10); 
}); 

jsfiddle上的示例与提供的CSS。

+0

工作出色! – 2011-03-02 19:21:56

0

最简单的方法是使用queue: true连续连续调用.animate调用,这将在前面的动画完成后为每个动画调整动画。例如:

$(this).animate({ top: "-=200"" }, { queue: true, duration: 3000 }) 
    .animate({ top: "-=200"" }, { queue: true, duration: 3000 }) 
    .animate({ top: "-=200"" }, { queue: true, duration: 3000 }); 
// And so on. 

一个更优雅的解决办法是创建自己的$ .fn方法...

+0

谢谢Stef。增加了一些额外的引号,但修正后,动画不会反复循环,直到它达到600px – 2011-03-02 18:57:15

1

的一种方式做,这是由行为绑定到一个自定义事件,则触发该事件递归你递减计数器:

$('#featured li.block div').click(function() { 
    var times = 10; 
    $(this).bind('roll', function(){ // bind custom event 
    $(this).animate({ 
     top: "-=200" 
    }, 300, function() { 
     $(this).css('top', '220px').animate({ 
     top: "-=220" 
     }, 300, function() { // add callback function here 
     if (--times) { 
      $(this).trigger('roll'); // trigger custom event 
     } 
     }); 
    }); 
    }).trigger('roll'); // first trigger to start the process 
}); 

例子:http://jsfiddle.net/redler/Nnt3j/

+0

哇,壁橱呢!谢谢肯,这可以轻松地与缓动插件集成在一起,使缓动开始缓慢,更快,然后再缓慢停止? – 2011-03-02 19:01:09

+0

@凯斯,如果你想让缓动作为一个单位来影响所有十个动画,那么这是一个更复杂的任务。那是你在找什么? – 2011-03-02 19:04:03

+0

啊,我想是的,但这不是什么大事。会很好,但非常感谢你已经给我的东西! – 2011-03-02 19:07:00