1.很多数据大屏的数据都需要数字变化时滚动加载,今天我们来简单实现,效果图如下
简单的介绍一下原理:
假如数字初始为1234567,我们把数字分割为数组[1,2,3,4,5,6,7],单独处理每一位,然后每一位数字都有自己对应的一个垂直排布的0-9的div容器用于滚动到当前需要展示的数字,因为一共有10个数字,如果需要展示数字几,就将外层容器的transform:translateY(-(需要展示的数字)*10%)进行移动,并且设置transition就行了。
这次我们用vue3来实现。
定义ScrollComponent组件。
<template>
<div class="content">
<div class="count_item" v-for="(item, index) in countRender" :key="index">/*当前展示的div,设置了overflow:hidden*/
<div class="icon" v-if="isNaN(Number(item))">{{ item }}</div>/*如果当前是逗号就直接渲染*/
<div v-else class="digital_wrap">/*否则需要渲染0-9一共10个垂直的div用于滚动*/
<div
:style="{
transition: 'transform 1s',
transform: `translateY(-${item * 10}%)`,
}"
>
<div
v-for="(items, index) in currentValRef.split('')"
:key="index"
class="digital"
> /*0-9的div容器*/
{{ items }}
</div>
</div>
</div>
</div>
</div>
</template>
<script setup>
import { ref ,computed} from "vue";
const props = defineProps({
count: {
type: String,
default: '00000000',
},
});
//将数字处理为每隔3位加一个逗号,用于美观
const countRender=computed(()=>{
return props.count.replace(/(?!^)(?=(\d{3})+$)/g,',')
})
const currentValRef = ref("0123456789");
</script>
<style lang="scss" scoped>
.content {
display: flex;
justify-content: space-between;
width: 800px;
align-items: center;
}
.icon {
font-size: 50px;
color: #fff;
height: 120px;
flex-direction: column;
display: flex;
justify-content: flex-end;
}
.digital_wrap {
width: 80px;
height: 120px;
background: url("../assets/chart_center_bg.png") no-repeat;//用于美观,使用的背景图片
background-size:100% 100%;
overflow: hidden;
}
.digital {
width: 100%;
font-size: 50px;
color: #fff;
height: 100%;
line-height: 120px;
}
</style>
然后我们在App.vue中去使用
<script setup>
import ScrollComponent from './components/ScrollComponent.vue'
import {ref,computed,onMounted} from 'vue'
const count=ref('1235489')
onMounted(() => {
setInterval(()=>{
count.value=`${Number(count.value)+123}`
},1500)
})</script>
<template>
<div class="wrap">
<ScrollComponent :count="count"></ScrollComponent>
</div>
</template>
<style scoped>
.wrap{
width: 100vw;
height:100vh;
display: flex;
justify-content: center;
align-items: center;
background:url('./assets/chart_bg.png') no-repeat;//用于美观,使用的背景
background-size:100% 100%;
}
.logo {
height: 6em;
padding: 1.5em;
will-change: filter;
transition: filter 300ms;
}
.logo:hover {
filter: drop-shadow(0 0 2em #646cffaa);
}
.logo.vue:hover {
filter: drop-shadow(0 0 2em #42b883aa);
}
</style>
完结!