0

有没有办法重用以下代码的参数?我只想设置duration: 750, easing: 'easeOutBack', queue: false一次,而不是在每个动画上设置。

    $("#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
         });
    });
4

4 回答 4

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);
});
于 2013-04-26T17:03:52.057 回答
0
var animParams = {
            duration: 750,
            easing: 'easeOutBack',
            queue: false
         };

$("#slide").animate({ left: "0" }, animParams);
$("#arrow").animate({ left: "-20px" }, animParams);
于 2013-04-26T17:03:47.310 回答
0

在父函数中创建一个对象:

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

然后将其放在动画函数中作为第二个参数

于 2013-04-26T17:04:13.817 回答
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);
});
于 2013-04-26T17:07:08.657 回答