编辑:这与这篇帖子How to reverse an animation on mouse out after hover不同。不同之处在于,在这种情况下,过渡状态(进展程度)是至关重要的,这与前面提到的完全忽略过渡的情况不同。
TL; DR:如何在动画结束后将元素动画化/转换回其原始状态?
你好
我正在尝试制作动画面板,以使其在悬停时“浮动”。我的问题是鼠标离开面板,而不是过渡回其原始状态,而是立即跳回。
此代码的简化版本可以在下面的代码段中找到。
body {
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
}
div {
width: 50px;
height: 50px;
background-color: red;
}
div:hover {
animation: float 2s infinite ease;
}
@keyframes float {
0%, 100% {
transform: none;
}
50% {
transform: translateY(-20px);
}
}
<html>
<head>
<title>animate to orignal position</title>
</head>
<body>
<div id='box'></div>
</body>
</html>
如您所见,浮动它会触发一个类似于浮动运动的平滑动画,但是,当鼠标离开该框并且动画停止时,它会突然中断。
所以我的问题是:有没有一种方法可以让盒子转换回其原始状态,最好不要使用JavaScript(尽管所有建议都值得赞赏)。
(这可能已经在网上某个地方得到了回答,如果是这种情况,那么我真的很抱歉,但我一直无法找到解决问题的合适方法。如果找到合适的解决方案,请添加重复的内容。 )
谢谢。
答案 0 :(得分:4)
您将不得不使用JavaScript和CSS过渡:
var box = document.getElementById('box')
var timer
box.addEventListener('mouseenter', function () {
box.classList.add('up')
timer = setInterval(function () {
box.classList.toggle('up')
}, 1000)
})
box.addEventListener('mouseleave', function () {
clearInterval(timer)
box.classList.remove('up')
})
body {
width: 100%;
height: 100vh;
margin: 0;
padding: 0;
display: flex;
justify-content: center;
align-items: center;
}
div {
width: 50px;
height: 50px;
background-color: red;
transition: transform 1s ease;
}
div.up {
transform: translateY(-20px);
}
<html>
<head>
<title>animate to orignal position</title>
</head>
<body>
<div id='box'></div>
</body>
</html>