简体   繁体   中英

Use HTML 5 data-attributes for left and right directional values

The following blocks of code are pretty much the same... the main diffirence between them would be the left and right directional values.

I would like to reduce the following code as much as possible, by possibly reusing one block of code for both .forward & .backward. I assume that we can use variables or the html5 data-attr to store values for left and right???

Thanks again everyone!

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

What the heck, I played with it a little and came up with:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM