对左右方向值使用HTML 5数据属性

时间:2012-05-26 20:27:04

标签: jquery animation

以下代码块几乎相同......它们之间的主要区别在于左右方向值。

我想尽可能地减少以下代码,可能会重复使用一个代码块.forward& 。向后。我假设我们可以使用变量或html5 data-attr来存储左和右的值???

再次感谢大家!

<div class="hover-area">
    Hover area
    <div class="backward">Backward</div>
    <div class="forward">Forward</div>
</div>

<style>
    a
.hover-area {
    position: relative;
}

.forward,
.backward {
    position: absolute;
}

</style>

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

1 个答案:

答案 0 :(得分:1)

到底是什么,我玩了一点,然后提出来:

$('.forward, .backward').css([$(this).is('.forward')?'right':'left'], 0).css('opacity', 0);
$('.hover-area').on('mouseenter mouseleave', function(evt) {
    $(this).find('.forward, .backward').each(function(i,elm) {
        var direction = {};
            direction[$(elm).is('.forward') ? 'right' : 'left'] = evt.type==='mouseleave'?0:20;
        $(elm).stop()
            .animate(direction, {queue:false, duration:300, easing:'easeOutCubic'})
            .animate({opacity: evt.type==='mouseleave'?0:0.95}, {queue:false, duration:400, easing:'easeOutCubic'});
    });
});​

DEMONSTRATION