基于Vue2实现数字纵向滚动效果
作者:芝麻小仙女
这篇文章主要为大家详细介绍了如何基于Vue2实现数字纵向滚动效果,从而达到显示计时器滚动效果,感兴趣的小伙伴可以跟随小编一起学习一下
需求:
在页面中显示一个数字,并在进入视口时显示计时器滚动效果:
效果如上
实现代码
新建组件ScrollNumber.vue:
<template> <div style=" display: inline-flex; justify-content: flex-start; align-items: center; " > <div v-for="(item, index) in numberList" :key="index" style=" display: inline-flex; justify-content: flex-start; align-items: center; padding-bottom: 0.3rem; box-sizing: border-box; " > <span v-if="isNaN(item)">{{ item }}</span> <div class="number" v-else> <span class="number-item" ref="numberItem" :data-number="item" :data-index="index" >0123456789</span > </div> </div> </div> </template> <script> export default { name: "ScrollNumber", props: { value: { type: [String, Number], default: 0, }, }, watch: { value(newVal) { if (newVal) { this.$nextTick(() => { this.setNumberTransform(); }); } }, }, computed: { numberList() { return String(this.value).split(""); }, }, data() { return { hasShow: false, // 是否已展示过动画 }; }, mounted() { window.addEventListener("scroll", this.scrollHandle, true); // 监听 监听元素是否进入/移出可视区域 }, methods: { scrollHandle() { const offset = this.$el.getBoundingClientRect(); const offsetTop = offset.top; const offsetBottom = offset.bottom; // 进入可视区域 if (offsetTop <= window.innerHeight && offsetBottom >= 0) { this.setNumberTransform(); this.hasShow = true; window.removeEventListener("scroll", this.scrollHandle, true); } else { // 移出可视区域 if (this.hasShow) { window.removeEventListener("scroll", this.scrollHandle, true); } } }, // 设置每一位数字的偏移 setNumberTransform() { let numberItems = this.$refs.numberItem; let obj = {}; Array.from(numberItems).forEach((c) => { let key = c.dataset.index; let value = c.dataset.number; let init = 0; obj[key] = setInterval(() => { if (init < value * 10) { init += 1; c.style.transform = `translateY(-${init}%)`; } else { clearInterval(obj[key]); obj[key] = null; } }, 8); }); }, }, }; </script> <style scoped lang="less"> .number { width: 0.42rem; height: 0.62rem; font-size: 0.56rem; font-weight: 800; color: #ffe52c; text-align: center; overflow: hidden; line-height: 0.42rem; > span { text-align: center; writing-mode: vertical-rl; text-orientation: upright; transform: translateY(0%); } } </style>
使用:
import ScrollNumber from "../ScrollNumber/ScrollNumber.vue";
<scroll-number :value="num.toString()"></scroll-number>
到此这篇关于基于Vue2实现数字纵向滚动效果的文章就介绍到这了,更多相关Vue2数字纵向滚动内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!