简体   繁体   English

将HTML 5数据属性用于左右方向值

[英]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. 我想通过可能为.forward和.backward重用一个代码块来尽可能减少以下代码。 I assume that we can use variables or the html5 data-attr to store values for left and right??? 我假设我们可以使用变量或html5数据属性来存储左和右的值???

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 示范

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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