2010-11-02 42 views
0

我有一個正常工作的jquery動畫腳本,但是,我覺得有一種方法可以減少腳本的總體開銷。這裏是一個鏈接到網頁發展:想要濃縮我的jquery動畫腳本

http://dev.abinstallations.com

有兩個部分的動畫,這些動畫應用到六個獨立的div元素。一個單獨的腳本應用於每個元素。例如:

//First 
$("#first_flip").hide(); 
$("#first_button_show").click(function(){ 
    $('#first_flip').animate({ 
    opacity: 'toggle', 
    top: '+=524', 
    height: 'toggle'}, 600, function() { 
     // Animation complete. 
    }); 
}); 
$("#first_button_hide").click(function(){ 
    $('#first_flip').animate({ 
    opacity: 'toggle', 
    top: '-=524', 
    height: 'toggle'}, 400, function() { 
     // Animation complete. 
    }); 
}); 

//Second 
$("#second_flip").hide(); 
$("#second_button_show").click(function(){ 
    $('#second_flip').animate({ 
    opacity: 'toggle', 
    top: '+=524', 
    height: 'toggle'}, 600, function() { 
     // Animation complete. 
    }); 
}); 
$("#second_button_hide").click(function(){ 
    $('#second_flip').animate({ 
    opacity: 'toggle', 
    top: '-=524', 
    height: 'toggle'}, 400, function() { 
     // Animation complete. 
    }); 
}); 

...等等其餘四個元素。有沒有一種凝聚的方式來實現這一目標?

+1

你發佈的鏈接已經死了..因爲所有按鈕的代碼都是相同的,所以它應該能夠將它濃縮到一個單獨的發生,但是我們需要首先看到html .. – 2010-11-02 17:52:10

+0

Gaby - 謝謝你的發現。新的鏈接是dev.abinstallationsinc.com – David 2010-11-17 02:23:49

回答

0

你可以把它作爲一個功能:

Hook("first"); 
Hook("second"); 

function Hook(id) 
{ 
    $("#" + id + "_flip").hide(); 
    $("#" + id + "_button_show").click(function(){ 
     $("#" + id "_flip").animate({ 
     opacity: 'toggle', 
     top: '+=524', 
     height: 'toggle'}, 600, function() { 
      // Animation complete. 
     }); 
    }); 
    $("#" + id + "_button_hide").click(function(){ 
     $("#" + id + "_flip").animate({ 
     opacity: 'toggle', 
     top: '-=524', 
     height: 'toggle'}, 400, function() { 
      // Animation complete. 
     }); 
    }); 
} 

甚至使功能需要幾個參數,並遍歷他們。

+0

Mikael,您的解決方案是完美的。非常感謝! – David 2010-11-08 03:44:54