uni-app实现数字动态变化的上下滚动动画效果

uni-app实现数字动态变化的上下滚动动画效果

数字动态变化的上下滚动的动画效果

1 回复

更多关于uni-app实现数字动态变化的上下滚动动画效果的实战教程也可以访问 https://www.itying.com/category-93-b0.html


uni-app 中实现数字动态变化的上下滚动动画效果,可以通过使用 CSS 动画和 JavaScript 结合来完成。下面是一个示例代码,展示了如何实现这一效果。

首先,在页面的 <template> 部分,我们定义一个显示数字的容器:

<template>
  <view class="container">
    <view class="number-box" :style="numberStyle">
      {{ currentNumber }}
    </view>
    <button @click="startAnimation">Start Animation</button>
  </view>
</template>

接下来,在 <script> 部分,我们定义数据和方法来控制数字的变化和动画:

<script>
export default {
  data() {
    return {
      currentNumber: 0,
      targetNumber: 100, // 目标数字
      animationFrameId: null,
    };
  },
  computed: {
    numberStyle() {
      return {
        animation: this.animationName + ' 2s infinite linear',
      };
    },
  },
  methods: {
    startAnimation() {
      if (this.animationFrameId) {
        cancelAnimationFrame(this.animationFrameId);
      }
      let startTime = null;
      const animate = (timestamp) => {
        if (!startTime) startTime = timestamp;
        const progress = timestamp - startTime / 2000; // 2秒动画时间
        this.currentNumber = this.lerp(0, this.targetNumber, progress);
        if (progress < 1) {
          this.animationFrameId = requestAnimationFrame(animate);
        } else {
          // 动画结束后重置
          this.currentNumber = this.targetNumber;
          this.resetAnimation();
        }
      };
      this.resetAnimation(); // 重置动画样式
      this.animationFrameId = requestAnimationFrame(animate);
    },
    lerp(a, b, t) {
      return a * (1 - t) + b * t;
    },
    resetAnimation() {
      // 可以通过修改 class 或者直接操作 style 来重置动画
      // 这里我们简单通过改变 animation-name 来触发新的动画周期
      this.animationName = `scrollAnimation_${Date.now()}`;
    },
  },
  data() {
    return {
      animationName: `scrollAnimation_${Date.now()}`,
    };
  },
};
</script>

最后,在 <style> 部分,我们定义一些基本的样式:

<style>
.container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100vh;
}

.number-box {
  font-size: 48px;
  font-weight: bold;
}
</style>

这个示例中,我们通过 requestAnimationFrame 实现平滑的数字过渡动画,并通过动态改变 animation-name 来重置 CSS 动画,从而循环播放动画。点击按钮后,数字将从 0 平滑过渡到 100,并在 2 秒内完成上下滚动的动画效果。

回到顶部