假设我有一个带有透明度的 HTML 元素。当我悬停在元素上时,它应该变成纯红色。当我停止悬停元素时,它应该动画化回第一个状态,但仅在 X 秒后。
到目前为止一切顺利,请参阅代码片段。
我的问题是当我停止悬停元素然后返回悬停它时。初始动画再次开始,但它尚未动画到初始状态尚未开始,因此从全彩色到透明,然后淡入全色,然后淡入全色。
有没有办法在没有JavaScript的情况下解决这个问题?
然后,通过将div 的背景设置为全色,可以保留不悬停时的颜色。但它也将其设置为初始颜色。我该如何解决这个问题?删除它只会在不悬停时删除颜色!
带有过渡的不透明度不是一种选择,因为我在这个div 中有内容。
div {
width: 100px;
height: 100px;
background: rgba(50, 60, 95, 1);
animation-name: fadeItOut;
animation-duration: 1s;
animation-delay: 2s;
animation-fill-mode: forwards;
}
div:hover {
animation-name: fadeItIn;
animation-duration: 1s;
animation-delay: 0s;
animation-fill-mode: forwards;
}
@keyframes fadeItIn {
0% {
background: rgba(50, 60, 95, 0.3);
}
100% {
background: rgba(50, 60, 95, 1);
}
}
@keyframes fadeItOut {
0% {
background: rgba(50, 60, 95, 1);
}
100% {
background: rgba(50, 60, 95, 0.3);
}
}
<div></div>
当transition
是更好的选择时,使用animation
可能会使事情复杂化。动画具有起点和终点(0%
和100%
关键帧),因此当您将鼠标悬停在或悬停时,元素首先设置为与0%
关键帧的状态(因为动画方向是正常的),然后继续到100%
关键帧。当您快速悬停在或悬停时(在上一个动画完成之前),由于关键帧道具的设置0%
您总是会看到这些跳跃。
下面应该是您需要的:
div {
width: 100px;
height: 100px;
background: rgba(50, 60, 95, 0.3);
transition-property: background;
transition-duration: 1s;
transition-delay: 2s;
}
div:hover {
background: rgba(50, 60, 95, 1);
transition-delay: 0s;
}
<div></div>
你的代码就可以工作了。
正如您所说,这种"可怕"效果只是因为您在动画淡出完成之前将鼠标悬停在元素上。
尝试像这样减少div 的动画延迟:
div {
width: 100px;
height: 100px;
background: rgba(50, 60, 95, 1);
animation-name: fadeItOut;
animation-duration: 1s;
animation-delay: 1s;
animation-fill-mode: forwards;
}
这是我为让你看到它而制作的小提琴:https://jsfiddle.net/oqyep7tt/
至少哈利的方式比这要好得多。
试试这个
div {
width: 100px;
height: 100px;
background: rgba(50, 60, 95, 1);
transition: background 300ms;
animation-name: fadeItOut;
animation-duration: 1s;
animation-delay: 0s;
animation-fill-mode: forwards;
}
div:hover {
animation-name: fadeItIn;
animation-duration: 1s;
animation-delay: 0s;
animation-fill-mode: forwards;
}
@keyframes fadeItIn {
0% {
background: rgba(50, 60, 95, 1);
}
100% {
background: rgba(50, 60, 95, 0.3);
}
}
@keyframes fadeItOut {
0% {
background: rgba(50, 60, 95, 0.3);
}
100% {
background: rgba(50, 60, 95, 1);
}
}
现场演示 - https://jsfiddle.net/rye2gnp3/