我创建了一个CSS浮动动画,用于将鼠标悬停在图像上。悬停时,图像很好地上下浮动,但是当我将鼠标移出时,动画不会以平滑的方式返回到原始状态。想法是,如果浮动增加,则在鼠标移开时图像将浮动回到“地面”水平。是否可以仅使用CSS来实现?
我试图将过渡添加到悬停状态,但是由于它是一个无限的浮动动画,因此它没有考虑图像的Y位置。如果将translateY设置为-4px,并且图像处于-9px位置,则会导致粗糙的mouseout效果。
.example-block {
background: red;
box-shadow: 0 27px 30px -15px rgba(21, 173, 250, 0.6);
transition: background 0.4s ease-out;
position: relative;
display: inline-block;
width: 100%;
height: auto;
}
.example-block:hover {
background: blue;
cursor: pointer;
animation: levitate 3s ease-in-out infinite;
}
@keyframes levitate-in {
from {
transform: translate(0, -4px);
box-shadow: 0 31px 30px -15px rgba(21, 173, 250, 0.3);
}
to {
transform: translate(0, 0px);
box-shadow: 0 27px 30px -15px rgba(21, 173, 250, 0.6);
}
}
@keyframes levitate {
0% {
transform: translate(0, 0px);
box-shadow: 0 27px 30px -15px rgba(21, 173, 250, 0.6);
}
50% {
transform: translate(0, -9px);
box-shadow: 0 36px 30px -15px rgba(21, 173, 250, 0.3);
}
100% {
transform: translate(0, 0px);
box-shadow: 0 27px 30px -15px rgba(21, 173, 250, 0.6);
}
}
.example-block a {
display: block;
position: absolute;
top: 0;
opacity: 0;
left: 0;
right: 500%;
bottom: 0;
transition: opacity 0.4s ease-out;
transform: translate(-50%, -50%);
}
.example-block:hover a {
opacity: 1;
right: 0;
transform: translateY(33%);
border-bottom: 0;
}
.example-block .image {
width: 100%;
height: auto;
transition: opacity 0.4s ease-out, transform 0.4s ease-out;
}
.example-block:hover .image {
opacity: 0.2;
transform: rotate(4deg) scale(1.1);
}
.example-block .svg {
max-width: 41px;
height: auto;
}
<div class="example-block p-5 text-center">
<img src="http://via.placeholder.com/350x150" alt="portfolio sample" class="image" />
<a href="#"><img src="http://via.placeholder.com/22x22" class="svg" /></a>
</div>