需求:项目中用到的轮播效果,要求文字类似覆盖式的显示隐藏。在这做个案例
分析:首先想到的是给文字天添加一个伪类after ,定位为absolute。隐藏时,after高度为文字框高,显示时after高度为0。
部分代码:
css:
.hero-name::after,
.hero-word::after{
content: '';
display: block;
bottom: 0px;
top: unset;
height: 100%;
left: 0px;
width: 100%;
position: absolute;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
background: gray;
height: 100%;
}
.hero-name[status=show]::after{
animation: show 1s ease both;
animation-delay: 0s;
}
.hero-word[status=show]::after{
animation: show 1s ease both;
animation-delay: 400ms;
}
.hero-name[status=hide]::after{
animation: hide 1s ease both;
animation-delay: 0s;
}
.hero-word[status=hide]::after{
animation: hide 1s ease both;
animation-delay: 400ms;
}
@keyframes show
{
from {bottom: 0px; top: unset; height: 100%;}
to {bottom: 0px; top: unset; height: 0%;}
}
@keyframes hide
{
from {top: 0px; bottom: unset; height: 0%;}
to {top: 0px; bottom: unset; height: 100%;}
}
html:
<div class="word-box">
<div class="word-item hero-name">上官婉儿</div>
<div class="word-item hero-word">逆风起笔,最能得势。</div>
</div>
效果:
BUG:对于纯色背景的还好,如果是加上了复杂的背景图就有大问题了。
复杂背景效果:
解决方案:
想了一个办法,使用css3的转换 transform: translateY 配合 overflow: hidden;来解决。
外框设置文字溢出隐藏overflow: hidden;,内框、外框通过设置transform: translateY不同值来实现文字的覆盖显示和隐藏,这样就可实现透底覆盖式文字消失隐藏效果了。
显示隐藏动画示意:
部分代码:
css:
.lu-showhide{
position: relative;
height: fit-content;
overflow: hidden;
transform: translateY(-100%);
display: inline-block;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
.lu-showhide-in{
position: relative;
transform: translateY(100%);
display: inline-block;
-webkit-animation-fill-mode: both;
animation-fill-mode: both;
}
.lu-showhide.show{
animation: pshow 1000ms ease both;
animation-delay: 0ms;
}
.show .lu-showhide-in{
animation: cshow 1000ms ease both;
animation-delay: 400ms;
}
.lu-showhide.hide{
animation: phide 1000ms ease both;
animation-delay: 0ms;
}
.hide .lu-showhide-in{
animation: chide 1000ms ease both;
animation-delay: 400ms;
}
@keyframes pshow
{
from {transform: translateY(-100%);}
to {transform: translateY(0%);}
}
@keyframes cshow
{
from {transform: translateY(100%);}
to {transform: translateY(0%);}
}
@keyframes phide
{
from {transform: translateY(0%);}
to {transform: translateY(100%);}
}
@keyframes chide
{
from {transform: translateY(0%);}
to {transform: translateY(-100%);}
}
html:
<div class="word-box">
<div class="hero-name lu-showhide">
<div class="lu-showhide-in">
上官婉儿
</div>
</div>
<div class="hero-word lu-showhide">
<div class="lu-showhide-in">
逆风起笔,最能得势。
</div>
</div>
</div>
效果:
这里为了方便使用,用到了自定义html标签,自定义了个组件。可自行下载源码查看。