如何在悬停元素时反转动画?

时间:2013-11-18 15:43:09

标签: css css3

我尝试使用translateY和CSS3动画在悬停时将按钮设置为其父元素的中心动画,这似乎工作正常(虽然任何建议改进都会很棒)但问题是我一徘徊在按钮不会反转动画而只是重置回-50px。想知道我怎么能做到这一点?

CSS(使用SCSS + Compass)

@include keyframe(slideIn) {
  0%{
    //opacity:0;
    -webkit-transform:translateY(-50px);
  }
  60%{ 
    //opacity:1;
    //-webkit-transform:translateY(-195px);
  }
  80%{
    -webkit-transform:translateY(-188px);
  }
  100%{
    -webkit-transform:translateY(-175px);
  }
}


.box {
  width: 300px;
  height: 300px;
  background: navy;
  position: relative;
  -webkit-transform: translate3d(0, 0, 0);
  overflow: hidden;

  &:hover {
    .btn {
      @include animation(slideIn .45s ease-in-out alternate forwards);
    }
  }
}

.btn {
  width: 50px;
  height: 50px; 
  position: absolute;
  bottom: -50px;
} 

Codepen - http://codepen.io/styler/pen/fpFlL

2 个答案:

答案 0 :(得分:1)

您可以定义3个css类:

.box{
   //base css here
}

.box.out{
     animation-name: out;
     animation-duration:.45s;
 }

 .box.over{
     animation-name: in;
     animation-duration:.45s;
 }

 @keyframe in {
     //your keyframe animation here
 }

 @keyframe out {
     //reverse animation here
 }

然后一些javascript来检测悬停:

$(".box").hover(
    function () {
        $(this).removeClass('out').addClass('over');
    },
    function () {
        $(this).removeClass('over').addClass('out');
    }
); 

答案 1 :(得分:1)

您应该将css动画放在按钮上而不是悬停上。

.box {
      width: 300px;
      height: 300px;
      background: navy;
      position: relative;
      -webkit-transform: translate3d(0, 0, 0);

      &:hover {
        .btn {
          bottom: 150px;

        }
      }
    }

    .btn {
      width: 50px;
      height: 50px; 
      position: absolute;
      bottom: -50px;  
      -webkit-transition-duration: 0.3s;
      -moz-transition-duration: 0.3s;
      -o-transition-duration: 0.3s;
      transition-duration: 0.3s;
    } 

http://codepen.io/anon/pen/qGxBh