在jQuery中悬停时停止并重新启动动画

时间:2011-03-16 14:21:58

标签: jquery animation loops hover restart

我正在尝试使用jQuery创建一个动画按钮,该按钮应该在悬停时停止,然后在没有悬停时重新启动。

对于动画,我使用的循环看起来像这样:

$(document).ready(function test() {
        $('#box').animate({opacity:0.5}, {duration:750})
        .animate({opacity:1}, {duration:1500})
        .animate({opacity:0.5}, {duration:750, complete: test})
        ;
    });

我尝试使用.stop()添加悬停但是,然后我不知道如何重新启动动画。你有什么建议吗?

另外,我在这里有一个小例子:http://jsfiddle.net/fTpZZ/

2 个答案:

答案 0 :(得分:2)

hover()事件处理程序可以分别处理handlerIn和handlerOut方法作为第一个和第二个参数。

悬停(handlerIn(eventObject),handlerOut(eventObject))

创建2个单独的函数 - 一个用于“on”状态,一个用于“off”

.hover() - jQuery API

答案 1 :(得分:1)

工作解决方案:(http://jsfiddle.net/fTpZZ/50/

$(document).ready(function()
    {
        $('#box').hover(function() {                   
            $('#box').stop();
            $('#box').animate({opacity:0},1);
        });

        function foo()
        {
            $('#box').animate({opacity:0.5}, 750, function(){
                $('#box').animate({opacity:1}, 1500, function(){
                    $('#box').animate({opacity:0.5}, 750, foo());    
                });
            });             
        }

        foo();          
    });