问题描述:

I have two animations which are practically identical... the difference between them is "left vs right" positioning. I would like to reuse the first block of code for both .forward and .backward... I'm guessing this could be done with the use of a HTML 5 data- attributes or maybe variables, but I'm not sure how to go about that.

 .hover-area { position:relative; width:100%; height:50px; }

.backward, .forward { position:absolute; }

.backward{ left:0px; }

.forward { right:0px; }​

<div class="hover-area">

Hover Area

<div class="backward" data-animate-on='{"left":"20"}' data-animate-off='{"left":"0"}'>Previous</div>

<div class="forward" data-animate-on='{"right":"20"}' data-animate-off='{"right":"0"}'>Next</div>

</div>

$('.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'});

});

网友答案:

Use the .data() function to obtain the data-attributes and use them in .animate():

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

Here's a DEMO.​

网友答案:

This seems like a good candidate for CSS3 transform animations. Add a single class forward or backward, without all the data attributes, and use CSS to specify the animation properties.

.goforward {
    left: 20px;
    transition-property: left;
    transition-duration: 3s;
}

Then just add/remove the class to begin the animation:

$(".forward").addClass("goforward");

Demo: http://jsfiddle.net/EMUcV/1/

相关阅读:
Top