这是我参与更文挑战的第3天,活动详情查看: 更文挑战
以下内容来自B站CodingStartup起码课的字体轮播图效果。跟着老师学习的第二天
实现效果
代码
元素结构
<h2>
Turn your living room into
<div class="mask">
<span data-show>a theater.</span>
<span>a gym.</span>
<span>a concert hall.</span>
<span>an arcade.</span>
</div>
</h2>
样式结构
<style>
:root{
--offset: 6px;
}
body{
display: flex;
align-items: center;
justify-content: center;
}
h2{
width: 980px;
font-size: 100px;
font-family: Helvetica;
line-height: 1.06;
letter-spacing: -0.02em;
color: #1d1d1f;
}
.mask{
height: 106px;
position: relative;
overflow: hidden;
/* border: 1px solid red; */
margin-top: var(--offset);
}
.mask span{
display: block;
position: absolute;
top: 100px;
padding-bottom: var(--offset);
background-size: 100% 100%;
-webkit-background-clip: text;
background-clip: content-text;
-webkit-text-fill-color: transparent;
background-repeat: no-repeat;
}
.mask span[data-show]{
transform: translateY(-100%);
transition: all .5s ease-in-out;
}
.mask span[data-up]{
transform: translateY(-200%);
transition: all .5s ease-in-out;
}
.mask span:nth-child(1) {
background-image: linear-gradient(45deg, #0ecffe 50%, #07a6f1);
}
.mask span:nth-child(2) {
background-image: linear-gradient(45deg, #18e198 50%, #0ec15d);
}
.mask span:nth-child(3) {
background-image: linear-gradient(45deg, #8a7cfb 50%, #633e9c);
}
.mask span:nth-child(4) {
background-image: linear-gradient(45deg, #fa7671 50%, #f45f7f);
}
</style>
逻辑结构
setInterval(function(){
let data_show = document.querySelector('span[data-show]')
let next = data_show.nextElementSibling || document.querySelector('span:first-child')
let up = document.querySelector('span[data-up]')
if(up){
up.removeAttribute('data-up')
}
data_show.removeAttribute('data-show')
data_show.setAttribute('data-up','')
next.setAttribute('data-show','')
},2000)
- 主要是实现字体上下滚动的效果,
data-show标记当前内容中显示的数据,data-up标记上一个显示的数据。 - 每两秒将当前显示的数据替换成上一个数据,然后将下一个元素替换成当前显示的数据,如果不存在下一个元素的时候就将该
mask中的第一个子元素作为下一个元素。 - 主要是利用
transform: translateY(-100%);和position: absolute;top:100px - 学习:
background-clip: text;:将背景剪切到文字上- 属性值包括:
padding-box|border-box|content-box|text
- 属性值包括: