我有一个在悬停时移动元素的css过渡,以及一个在悬停时旋转元素的动画。动画的延迟等于过渡持续时间,因此在过渡到正确的位置后,动画开始。然而,当我们将鼠标移走时,动画会停止,但不会向下过渡,效果很好。
在鼠标移开和动画结束后,有没有可能让它转回来?
您可以在这里看到一个示例:http://codepen.io/jhealey5/pen/zvXBxM
简化代码如下:
div {
width: 200px;
height: 200px;
margin: 40px auto;
background-color: #b00;
position: relative;
&:hover {
span {
transform: translateY(-60px);
animation-name: rotate;
animation-duration: 1s;
animation-delay: .5s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
}
}
span {
position: absolute;
width: 20px;
height: 20px;
background-color: #fff;
bottom: 10px;
left: 0;
right: 0;
margin: auto;
transition: .5s;
}
@keyframes rotate {
from {
transform: translateY(-60px) rotate(0);
}
to {
transform: translateY(-60px) rotate(-90deg);
}
}发布于 2015-11-20 23:15:50
我已经派生了你的项目,并对其进行了调整,使其能够正常工作。You can find it here.
我所做的更改如下:
我将白色方块的起始位置设置为top: 150px,并让它在hover of div上获得一个top: 0。跨度得到一个transition: top .5s,在鼠标离开时,它在悬停时转到top: 0;,并返回到top: 150px;。
我已经从动画中删除了translateY(-60px);,因为当animation启动时,它会向上移动更多。
这是你的新CSS:
div {
width: 200px;
height: 200px;
margin: 40px auto;
background-color: #b00;
position: relative;
&:hover {
span {
top: 0px;
animation: rotate 1s infinite .5s alternate;
animation-direction: alternate;
}
}
}
span {
position: absolute;
width: 20px;
height: 20px;
background-color: #fff;
bottom: 10px;
left: 0;
right: 0;
top: 150px;
margin: auto;
transition: top .5s;
}
@keyframes rotate {
from {
transform: rotate(0);
}
to {
transform: rotate(-90deg);
}
}编辑:问题是动画是基于时间的,而不是基于动作的,这意味着只要你触发一个动画,计时器就会开始运行,它会运行所有的keyframes,直到设置的时间过去。除了计时器可以提前停止之外,悬停和悬停没有任何效果,但动画在此之后将不会继续(或反转,这是您所希望的)。transition是基于动作的,这意味着每次发生动作(例如:hover)时都会触发它。在:hover上,这意味着.5s需要转到top:0,当悬停结束时,.5s需要转到top:150px。
我希望上面的添加是有意义的:)
如你所见,我还清理了你的animation-name:等代码,因为它可以合并到一行中。
发布于 2015-11-20 23:14:08
作为Harry pointed out,问题是您正在动画/过渡相同的属性,在本例中为transform。看起来当前版本的Chrome/FF将允许animation控制该属性,从而破坏transition。似乎解决这个问题的唯一方法就是转换/动画一个不同的属性。由于需要继续旋转元素,因此可以通过更改bottom属性来平移/定位元素。我知道这不会产生完全相同的结果,但尽管如此,它确实移动了元素(只是不是相对于父元素)。
div:hover span {
bottom: 80px;
}作为另一种选择,您也可以包装span元素,然后转换该元素。
在下面的示例中,.wrapper元素在悬停时转换为translateY(-60px),然后旋转span子元素并保持动画。
div {
width: 200px;
height: 200px;
margin: 40px auto;
background-color: #b00;
position: relative;
}
div:hover .wrapper {
transform: translateY(-60px);
}
div:hover .wrapper span {
animation-name: rotate;
animation-duration: 1s;
animation-delay: .5s;
animation-iteration-count: infinite;
animation-direction: alternate;
}
.wrapper {
display: inline-block;
transition: .5s;
position: absolute;
bottom: 10px;
left: 0;
right: 0;
text-align: center;
}
.wrapper span {
display: inline-block;
width: 20px;
height: 20px;
background-color: #fff;
}
@keyframes rotate {
from {
transform: rotate(0);
}
to {
transform: rotate(-90deg);
}
}<div>
<span class="wrapper">
<span></span>
</span>
</div>
https://stackoverflow.com/questions/33829469
复制相似问题