0

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

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

2 回答 2

1

使用该.data()函数获取数据属性并将它们用于.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'});
    });

这是一个演示。​</p>

于 2012-09-01T02:57:20.213 回答
1

这似乎是 CSS3 变换动画的不错选择。添加单个类forwardbackward,不包含所有数据属性,并使用 CSS 指定动画属性。

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

然后只需添加/删除类即可开始动画:

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

演示:http: //jsfiddle.net/EMUcV/1/

于 2012-09-01T02:59:15.960 回答