我正在参加「兔了个兔」创意投稿大赛,详情请看:「兔了个兔」创意投稿大赛
前言
新的一年首先祝大家新年快乐,今天使用html+css+js制作一个轮播字祝福送给大家,希望大家在新的一年里兔年行大运
实现轮播字祝福
html部分添加一个h2标签来设定标题字的内容,然后再新增一个div标签来用作轮播字的容器,里面新增4个span标签来用作轮播字的内容
<h2>
在新的一年里格斗家
<div class="mask">
祝您:
<span data-show>心想事成</span>
<span>四季平安</span>
<span>招财进宝</span>
<span>红红火火</span>
</div>
</h2>
来到css部分,使用flex布局将h2标签固定在网页中间,设置h2标签的文字大小,行距以及字体间距等样式 ,然后设置.mask选择器,高度设为和h2行距一样,position为relative,因为一会会将span标签设为绝对定位,overflow设为超出隐藏
h2 {
width: 980px;
font-size: 100px;
font-family: Helvetica;
line-height: 1.06;
letter-spacing: -0.02em;
color: #fff;
}
.mask {
height: 106px;
position: relative;
overflow: hidden;
}
再新增.mask span选择器设置绝对定位,四组轮播字就会重叠在一起,所以设置top为106px将文字移到下方,空出一行的位置用来显示当前的轮播字
.mask span {
display: block;
box-sizing: border-box;
position: absolute;
top: 106px;
left: 250px;
}
回到html给第一个span加上data-show属性,然后在css加入.mask span[data-show]选择器,拥有data-show属性的span标签将文字平移到上方。当第二组轮播字向上移的时候第一组也要向上移,将第二个span加上data-show,第一个改为data-up,css也要增加相应的.mask span[data-up]选择器
.mask span[data-show] {
transform: translateY(-100%);
transition: .5s transform ease-in-out;
}
.mask span[data-up] {
transform: translateY(-200%);
transition: .5s transform ease-in-out;
}
然后设置文字的颜色,给对应的文字设定一个我认为比较配的颜色,于是给每个span都加上了渐变色,于是.mask span选择器加上background-clip: text用文字作为遮色片,然后将文字颜色设为透明色
.mask span {
background-size: 100% 100%;
-webkit-background-clip: text;
background-clip: text;
-webkit-text-fill-color: transparent;
background-repeat: no-repeat;
}
.mask span:nth-child(1) {
background-image: linear-gradient(45deg, #C04848 50%, #480048);
}
.mask span:nth-child(2) {
background-image: linear-gradient(45deg, #b8f4ac 50%, #30E20B);
}
.mask span:nth-child(3) {
background-image: linear-gradient(45deg, #f8f38d 50%, #fbee00);
}
.mask span:nth-child(4) {
background-image: linear-gradient(45deg, #fa7671 50%, #f40e0e);
}
最后来到js部分,轮播字是会重复执行的于是设置一个定时执行函数setInterval,每2000毫秒执行一次,在里面定义一个show变量,保存具有data-show属性的元素,在定义一个next变量用来赋值为show元素用一层的下一个元素,如果show为最后一个就改为获取第一个元素,再定义up变量保存具有data-up属性的元素的
如果up如果有值就移除data-up,就是元素已经在上面了,移除data-up属性就可以让这个元素回到下面,然后将show的data-show移除,给它加上data-up属性,就是当前元素已经在中间了,将它移到上面,而next也就是下一个元素,给他加上data-up,即是将下一个元素移到中间,这样轮播字祝福就实现了
setInterval(function () {
const show = document.querySelector('span[data-show]')
const next = show.nextElementSibling || document.querySelector('span:first-child')
const up = document.querySelector('span[data-up]')
if (up) {
up.removeAttribute('data-up')
}
show.removeAttribute('data-show')
show.setAttribute('data-up', '')
next.setAttribute('data-show', '')
}, 2000)
最后实现的效果放上了码上掘金