klren0312 / daliy_knowledge

知识积累,正确使用方式是watch
21 stars 4 forks source link

js 数字随机动态变化 / 滚动变化 / 动态累加 #78

Open klren0312 opened 5 years ago

klren0312 commented 5 years ago

1

<div class="number">0</div>
<div class="random">0</div>
<button onclick="stopRandom()">stopRandom</button>
<button onclick="startRandom()">startRandom</button>
var startNum = 0
  var endNum = 1000
  var num = document.querySelector('.number')
  function add () {
    ++startNum
    num.innerHTML = startNum
    if (startNum < 1000) {
      window.requestAnimationFrame(add)
    }
  }
  window.requestAnimationFrame(add)

  var randomStart = 000
  var random = document.querySelector('.random')
  var randomId = ''
  function randomF () {
    randomStart = Math.floor(Math.random() * (1000 - 99)) + 99
    random.innerHTML = randomStart
    randomId = window.requestAnimationFrame(randomF)
  }
  randomId = window.requestAnimationFrame(randomF)
  function stopRandom () {
    window.cancelAnimationFrame(randomId)
  }
  function startRandom () {
    randomId = window.requestAnimationFrame(randomF)
  }
klren0312 commented 3 years ago

Vue组件

<template>
  <div class="number">{{ calcValue }}</div>
</template>
<script>
export default {
  name: 'NumRun',
  props: {
    value: {
      type: Number
    },
    start: {
      type: Boolean,
      default: false
    }
  },
  data() {
    return {
      calcValue: 0,
      isFinish: false,
      timer: null
    }
  },
  mounted() {
    if (this.start && this.value !== this.calcValue) {
      this.run()
    }
  },
  beforeDestroy() {
    this.calcValue = this.value
  },
  deactivated() {
    this.calcValue = this.value
  },
  methods: {
    add() {
      if (this.calcValue >= this.value) {
        this.calcValue = this.value
        this.isFinish = true
      } else {
        this.calcValue += 1
      }
    },
    run() {
      const tick = () => {
        this.add()
        this.timer = requestAnimationFrame(this.run)
        if (this.isFinish) {
          this.timer && cancelAnimationFrame(this.timer)
          this.timer = null
        }
      }
      tick()
    }
  },
  watch: {
    start(nv) {
      if (nv && this.value !== this.calcValue) {
        this.run()
      }
    }
  }
}
</script>
<style lang=""></style>
klren0312 commented 3 years ago

https://github.com/inorganik/countUp.js

klren0312 commented 3 years ago

https://github.com/PanJiaChen/vue-countTo