我在页面加载时有多个宽度为零的 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/
最佳答案
解决这个问题的一种方法是使用包装器,为初始外观设置动画,然后在悬停时扩大和缩小包装器,子级将跟随其父级的宽度,
否则使用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>
关于html - CSS 动画,悬停时播放然后反转动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50067334/