1

我有两个几乎相同的动画......它们之间的区别是“左右”定位。我想为 .forward 和 .backward 重用第一个代码块......我猜这可以通过使用数据或变量来完成,但我不确定如何去做。

谢谢您的帮助

$('.forward').css({opacity:0, right:0});
$('.hover-area').hover(function() {
    $(this).find('.forward').stop()
        .animate({right:20}, {queue:false, duration:300, easing:'easeOutCubic'})
        .animate({opacity:'0.95'}, {queue:false, duration:400, easing:'easeOutCubic'});
},function() {
    $(this).find('.forward').stop()
        .animate({right:0}, {queue:false, duration:550, easing:'easeOutSine'})
        .animate({opacity:'0'}, {queue:false, duration:300, easing:'easeOutSine'});
});

$('.backward').css({opacity:0, left:0});
$('.hover-area').hover(function() {
    $(this).find('.backward').stop()
        .animate({left:20}, {queue:false, duration:300, easing:'easeOutCubic'})
        .animate({opacity:'0.95'}, {queue:false, duration:400, easing:'easeOutCubic'});
},function() {
    $(this).find('.backward').stop()
        .animate({left:0}, {queue:false, duration:550, easing:'easeOutSine'})
        .animate({opacity:'0'}, {queue:false, duration:300, easing:'easeOutSine'});
});
4

1 回答 1

0

您可以创建一个新的 jQuery 函数并为代码上两个段之间的每个差异传递变量。

$.fn.setupAnimation = function(selector, direction) {
    return this.hover(function() {
        var startData = {};
        startData[direction] = 20;

        $(this).find(selector).stop()
            .animate(startData, {queue:false, duration:300, easing:'easeOutCubic'})
            .animate({opacity:'0.95'}, {queue:false, duration:400, easing:'easeOutCubic'});
    }, function() {
        var startData = {};
        startData[direction] = 0;

        $(this).find(selector).stop()
            .animate(startData, {queue:false, duration:550, easing:'easeOutSine'})
            .animate({opacity:'0'}, {queue:false, duration:300, easing:'easeOutSine'});
    });
}

$('.hover-area').setupAnimation('.forward', 'right');
$('.hover-area').setupAnimation('.backward', 'left');
于 2012-05-26T08:09:08.243 回答