CSS动画,播放然后在悬停时反转动画

时间:2018-04-27 17:17:03

标签: html css css-animations

我在页面加载时有多个div零宽度,然后通过像这样的关键帧转换扩展(在页面加载之后)(例如)。每个div都有不同的最终宽度。

@keyframes growN {
    from {width: 0px;}
    to {width: 21vw;}
}

我想添加第二个动画,在悬停时将div进一步扩展(固定值),并在de hover(un-hover?)上将其设置回原始(后页加载动画)宽度。像这样:

@keyframes hover_grow {
    from {width: element.width;}
    to {width: 50vw;}
}

由于有很多div,我自己不做数学运算(每个div都有单独的动画,用自己的宽度代替element.width)。

我尝试了以下内容:

bar:hover {
    -webkit-animation-name: hover_grow;
    -webkit-animation-duration: 0.1s;
    -webkit-animation-timing-function: ease-out;
    -webkit-animation-direction: alternate;
    animation-name: grow;
    animation-duration: 1s;
    animation-timing-function: ease-out;
    animation-direction: alternate;
}

@-webkit-keyframes hover_grow {
    from {width: initial;}
    to {width: 25vw;}
}

@keyframes hover_grow {
    from {width: initial;}
    to {width: 25vw;}
}

这适用于悬停 - div进一步扩展,但在de hover时,它将其返回到其页面加载,预动画值(即0),并再次触发其页面加载动画。此外,时间似乎被忽略了。

JSFiddle:https://jsfiddle.net/an1o4brL/3/

1 个答案:

答案 0 :(得分:1)

解决这个问题的一种方法是使用包装器,为初始外观设置动画,然后在悬停时增大和缩小包装器,子项将遵循其父项的宽度,

其他明智的使用js

#bar4 {
  height: 30px;
  transition: width .5s linear;
  display: block;
  animation-name: grow4;
  animation-duration: .5s;
  animation-timing-function: ease-out;
  animation-iteration-count: 1;
  background-color: white;
  border: 2px solid #5e0734;
  margin-top: 0.15vh;
  margin-bottom: 0.15vh;
  margin-left: 0.5vh;
  overflow: hidden;
}

@keyframes grow4 {
  from {
    width: 0;
  }
  to {
    width: 100%;
  }
}

#bar4Wrap {
  width: 21vw;
  transition: width .5s linear;
}

#bar4Wrap:hover {
  width: 100%;
}
<div id="bar4Wrap">
  <a href="link" id="bar4">Link</a>
</div>