2010-01-25 141 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; 
});