2013-04-26 54 views
0

有什麼方法可以重用以下代碼的參數嗎?我只想設置duration: 750, easing: 'easeOutBack', queue: false而不是每個動畫。重複使用jQuery動畫參數

$("#box1").hover(function(){ 
     $("#slide").animate({ left: "0" },{ 
      duration: 750, 
      easing: 'easeOutBack', 
      queue: false 
     }); 
     $("#arrow").animate({ left: "-20px" },{ 
      duration: 750, 
      easing: 'easeOutBack', 
      queue: false 
     }); 
    }); 
    $("#box2").hover(function(){ 
     $("#slide").animate({ left: "-200px" }, { 
      duration: 750, 
      easing: 'easeOutBack', 
      queue: false 
     }); 
     $("#arrow").animate({ left: "-40px" },{ 
      duration: 750, 
      easing: 'easeOutBack', 
      queue: false 
     }); 
    }); 

回答

2
var obj = { 
      duration: 750, 
      easing: 'easeOutBack', 
      queue: false 
     }; 

$("#box1").hover(function(){ 
    $("#slide").animate({ left: "0" }, obj); 
    $("#arrow").animate({ left: "-20px" }, obj); 
}); 

$("#box2").hover(function(){ 
    $("#slide").animate({ left: "-200px" }, obj); 
    $("#arrow").animate({ left: "-40px" }, obj); 
}); 
+0

爾加!以秒擊敗我。 – j08691 2013-04-26 17:04:41

+0

@ j08691 - 我猜這是輪到我了! – adeneo 2013-04-26 17:05:30

+0

哇,你們快!我嘗試了類似的東西,但我想我的語法錯了。感謝您及時的回覆!我會盡快接受你的回答。 – Staysee 2013-04-26 17:08:11

0
var animParams = { 
      duration: 750, 
      easing: 'easeOutBack', 
      queue: false 
     }; 

$("#slide").animate({ left: "0" }, animParams); 
$("#arrow").animate({ left: "-20px" }, animParams); 
0

使父函數的對象:

var mySettings = { 
      duration: 750, 
      easing: 'easeOutBack', 
      queue: false 
     } 

然後將其放置在該動畫的功能作爲第二個參數

0

你可以清理了很多不止如此:

function animateWithEase($id,$left,$duration,$easing,$queue){ 
    $id.animate({left:$left},{ 
     duration:$duration, 
     easing:$easing, 
     queue:$queue 
    }); 
} 

$("#box1").hover(function(){ 
    animateWithEase($('#slide'),0,750,'easeOutBack',false); 
    animateWithEase($('#arrow'),-20,750,'easeOutBack',false); 
}); 
$("#box2").hover(function(){ 
    animateWithEase($('#slide'),-200,750,'easeOutBack',false); 
    animateWithEase($('#arrow'),-40,750,'easeOutBack',false); 
}); 

這使得參數的修改容易,如果你想在以後定製一個或多個,並且還可以很容易地應用到其他項目。

如果你想簡化它知道它會不會在以後的定製::

function animateWithEase($id,$left){ 
    $id.animate({left:$left},{ 
     duration:750, 
     easing:'easeOutBack', 
     queue:false 
    }); 
} 

$("#box1").hover(function(){ 
    animateWithEase($('#slide'),0); 
    animateWithEase($('#arrow'),-20); 
}); 
$("#box2").hover(function(){ 
    animateWithEase($('#slide'),-200); 
    animateWithEase($('#arrow'),-40); 
});