解决方案1 – 在第一个悬停上添加动画
可能最好的选择是不要放下下来的动画,直到用户首次盘旋在容器上。
这涉及监听鼠标悬停事件,然后在该点添加具有动画的类,并删除事件侦听器。主要(潜在的)缺点是它依赖于Javascript。
;(function(){
var c = document.getElementById('container');
function addAnim() {
c.classList.add('animated')
// remove the listener,no longer needed
c.removeEventListener('mouSEOver',addAnim);
};
// listen to mouSEOver for the container
c.addEventListener('mouSEOver',addAnim);
})();
#container {
position:relative;
width:100px;
height:100px;
border-style:inset;
}
#content {
position:absolute;
top:100px;
width:100%;
height:100%;
background-color:lightgreen;
opacity:0;
}
/* This gets added on first mouSEOver */
#container.animated #content {
-webkit-animation:animDown 1s ease;
}
#container:hover #content {
-webkit-animation:animUp 1s ease;
animation-fill-mode:forwards;
-webkit-animation-fill-mode:forwards;
}
@-webkit-keyframes animUp {
0% {
-webkit-transform:translateY(0);
opacity:0;
}
100% {
-webkit-transform:translateY(-100%);
opacity:1;
}
}
@-webkit-keyframes animDown {
0% {
-webkit-transform:translateY(-100%);
opacity:1;
}
100% {
-webkit-transform:translateY(0);
opacity:0;
}
}
解决方案2 – 播放动画隐藏
另一种方法是最初隐藏元素,确保动画在隐藏时播放,然后使其可见。这样做的缺点是,时机可能会稍微偏离,并且显得太早了,而且悬停也不可用。
这需要一些等待动画长度的Javascript,然后使#内容可见。这意味着您还需要将初始不透明度设置为0,因此它不会显示在加载中,并且还会从关键帧中删除可见性 – 这些操作无效:
// wait for the animation length,plus a bit,then make the element visible
window.setTimeout(function() {
document.getElementById('content').style.visibility = 'visible';
},1100);
#container {
position:relative;
width:100px;
height:100px;
border-style:inset;
}
#content {
visibility:hidden;
-webkit-animation:animDown 1s ease;
position:absolute;
top:100px;
width:100%;
height:100%;
background-color:lightgreen;
opacity:0;
}
#container:hover #content {
-webkit-animation:animUp 1s ease;
animation-fill-mode:forwards;
-webkit-animation-fill-mode:forwards;
}
@-webkit-keyframes animUp {
0% {
-webkit-transform:translateY(0);
opacity:0;
}
100% {
-webkit-transform:translateY(-100%);
opacity:1;
}
}
@-webkit-keyframes animDown {
0% {
-webkit-transform:translateY(-100%);
opacity:1;
}
100% {
-webkit-transform:translateY(0);
opacity:0;
}
}
解决方案3 – 使用转换
在您的情况下,您可以通过替换关键帧来替代这个CSS,因此它以不透明度开始:0,只是悬停在不透明度和变换中有变化:
#container {
position:relative;
width:100px;
height:100px;
border-style:inset;
}
#content {
position:absolute;
top:100px;
width:100%;
height:100%;
background-color:lightgreen;
/* initial state - hidden */
opacity:0;
/* set properties to animate - applies to hover and revert */
transition:opacity 1s,transform 1s;
}
#container:hover #content {
/* Just set properties to change - no need to change visibility */
opacity:1;
-webkit-transform:translateY(-100%);
transform:translateY(-100%);
}