2010-01-25 164 views
4

我有一个div元素,点击事件时,链接滑入。这很好,除了我现在试图获得它,以便如果再次单击链接,动画逆转到其原始状态。第二次点击jQuery倒车动画

我试图给链接添加一个类,但是当动画运行时,它最终会做同样的动画,但会倒退。

$('a.contact').click(function() { 
     $('#contact').animate({marginLeft:'500px'}, {queue:false, duration:'7000'}); 
     $('#contact').animate({width:'500px'}, {duration:'7000'}); 
     $('a.contact').css() 
     $('a.contact').animate({marginLeft:'-500px'}, '250'); 
     $('a.contact')addClass('open'); 
    return false; 
}); 
+0

如果这是你的代码,你就错过了一段 还,使用链接 – davidosomething 2010-01-25 12:15:36

回答

27

最简单的处理方法是使用jQuery切换。这使您可以通过交替点击激活两项功能。

$('a.contact').toggle(
function(){ 
    // odd clicks 
}, 
function(){ 
    // even clicks 
}); 

...还有一个快速的jsFiddle to demonstrate

请注意,这使用jQuery's toggle event handler,而不是相同名称的动画效果。

注意#2:根据文档,在jQuery 1.9中删除了toggle()。 (也就是说,方法签名允许您传递多个被交替点击激活的功能。)

1

首先,您缺少a。在addClass行中。这是正确的版本: $('a.contact')。addClass('open');

无论如何,我会做这样的:

// Bind the click event with the live function 

$('a.contact:not(.open)').live('click', function() { 
    // Animate box as wanted and add a class to indicate that the box is open. 
    // ... Code to animate goes here ... 
    $(this).addClass('open'); 
}); 

$('a.open').live('click', function() { 
    // Reverse animation and remove class 
    // ... Code to reverse animation goes here ... 
    $(this).removeClass('open'); 
}); 

,你需要与肝功能绑定的原因是出类“开放”不添加任何元素时的常规。点击()绑定发生。

阅读有关的活动方法在这里:http://api.jquery.com/live/

+1

应当指出的是.live()是不赞成的jQuery V1的.7并从v1.9开始删除 – Luke 2015-02-04 05:58:13

0
$('a.contact').click(function(e) { 
    e.stopPropagation(); 
    var dir = ''; 

    if ($(this).hasclass('to-left')) 
    { 
     dir = 'to-rigth'; 
     $(this).removeClass('to-left'); 
    } 
    else //ini or has class to rigth 
    { 
     dir = 'to-left'; 
     $(this).removeClass('to-rigth'); 
    } 

    dir = $(this).addclass(dir); 

    if (dir=='to-left') 
    { 
     //you code to left 
    } 
    else 
    { 
     //you code to rigth 
    } 

    return false; 
});