需求:
在页面中显示一个数字,并在进入视口时显示计时器滚动效果:
效果如上 ↑
新建组件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>
p.s.本篇copy了网上大佬的代码,打个点方便以后继续copy
标签:obj,key,效果,ScrollNumber,value,let,vue2,rem,计时器 From: https://www.cnblogs.com/nangras/p/17730371.html