1,首先是CSS核心点,利用writing-mode: vertical-lr; text-orientation:upright;
把文本设置为竖向排列,详细代码如下:
.scroll-time-container {
display: flex;
justify-content: center;
align-items: center;
font-size: 25px;
}
.scroll-time-wrap {
line-height: 1;
height: 30px;
overflow: hidden;
}
.scroll-time {
line-height: 0.6;
writing-mode: vertical-lr;
text-orientation: upright;
transform: translateY(0%);
transition: all .3s ease-in-out;
}
2,实现基本样式,示例如下:
3,HTML模板代码:
<div class="scroll-time-container">
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[0]}0%)`}">0123456789</div>
</div>
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[1]}0%)`}">0123456789</div>
</div>
月
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[2]}0%)`}">0123456789</div>
</div>
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[3]}0%)`}">0123456789</div>
</div>
日
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[4]}0%)`}">0123456789</div>
</div>
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[5]}0%)`}">0123456789</div>
</div>
:
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[6]}0%)`}">0123456789</div>
</div>
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[7]}0%)`}">0123456789</div>
</div>
:
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[8]}0%)`}">0123456789</div>
</div>
<div class="scroll-time-wrap">
<div class="scroll-time" :style="{transform: `translateY(-${scrollTimeData[9]}0%)`}">0123456789</div>
</div>
</div>
4,JS核心代码:
startScroll() {
let scroll = () => {
let date = new Date();
let dateStr = '';
let s = date.getSeconds();
s = s > 9 ? s : '0' + s;
let m = date.getMinutes();
m = m > 9 ? m : '0' + m;
let h = date.getHours();
h = h > 9 ? h : '0' + h;
let d = date.getDate();
d = d > 9 ? d : '0' + d;
let M = date.getMonth() + 1;
M = M > 9 ? M : '0' + M;
dateStr = M + d + h + m + s;
this.scrollTimeData = dateStr.split('');
}
scroll();
this.timer = setInterval(() => {
scroll();
}, 1000)
}
思路分析:
获取当前时间的时分秒,小于10补0,dateStr.split(‘’)得到数组["0", "2", "1", "7", "1", "5", "5", "5", "5", "9"]
,看到这里,想必大家已经很明白了吧,数组对应的就是HTML模板中的 scrollTimeData[0]
到 scrollTimeData[9]
。由于设置了过渡属性transition: all .3s ease-in-out;
因此数组中每个数字发生变化,内联样式:style="{transform: translateY(-${scrollTimeData[xxx]}0%)
}"的值发生变化时,便会产生一个滚动的效果。
注意:
离开页面记得使用clearInterval(this.timer);
清除定时器,否则会重复生成定时器。