【问题标题】:CSS animation, play and then reverse animation on hoverCSS动画,播放然后在悬停时反转动画
【发布时间】:2018-04-28 02:26:00
【问题描述】:

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

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

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

@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 进一步扩展,但在取消悬停时,它会将其返回到其页面加载、动画前值(即 0),并且其页面加载动画再次触发。此外,时间似乎被忽略了。

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

【问题讨论】:

    标签: html css css-animations


    【解决方案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>

    【讨论】:

      猜你喜欢
      • 2012-02-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-27
      • 2020-04-04
      • 2016-12-06
      • 2016-04-25
      • 2019-07-15
      相关资源
      最近更新 更多