命名空间动画

时间:2011-09-24 18:19:57

标签: jquery

是否可以命名动画?具体来说,我的问题是在给定元素$myElement上我正在做两种类型的动画。现在我想只对其中一种类型使用.stop(),而不是两种类型。

我该怎么做?

修改

此处提供的代码:http://jsfiddle.net/y34ME/1/

我的问题是,当我点击span我希望它消失时,无论我是否mouseout。目前,mouseout由于.stop()而中断了消失,但我需要.stop()来阻止mouseovermouseout事件排队。

3 个答案:

答案 0 :(得分:2)

您是否有理由需要使用委托?这段代码似乎可以做你想要的:

$("span").hover(
    function() {
        $(this).animate({backgroundColor: "blue"}, 1000);
    },
    function() {
        $(this).animate({backgroundColor: "white"}, 1000);
    }
);

$("span").click(function() {
    $(this).animate({backgroundColor: "green"}, 1000).fadeTo(2000, 0);
});

答案 1 :(得分:2)

只需使用undelegate。对于更干净的代码,它也可以封装在一个委托调用中。

  $('p').delegate('span',{
                'mouseover':function(e){  
       $(this).stop(true, true).animate({backgroundColor: 'blue'}, 1000);
                 },
                'mouseout':function(e){
       $(this).stop(true, true).animate({backgroundColor: 'white'}, 1000);
                },
                'click':function(e){
       $(this).animate({backgroundColor: 'green'}, 1000).fadeTo(2000, 0).undelegate( 'mouseout' );
                }

                });

答案 2 :(得分:2)

我认为你真正想要的是,如果你已经将元素消失了,根本不会触发鼠标输出。 Andrew的方法效果很好,但是如果你想让你的事件处理程序保持不变(例如,如果有办法再次显示这个元素),请使用状态类:

$('p').delegate('span:not(.hidden)', {
    'mouseover': function () {
       $(this).stop(true, true).animate({backgroundColor: 'blue'}, 1000);
    },
    'mouseout':function () {
       $(this).stop(true, true).animate({backgroundColor: 'white'}, 1000);
    },
    'click': function () {
       $(this).addClass('hidden').stop(true, true).animate({backgroundColor: 'green'}, 1000).fadeTo(2000, 0);
    }
});

http://jsfiddle.net/y34ME/4/