Vue 数字滚动

HTML部分

<span
     class="delivery"
     :data-min="0"
      :data-max="100" //目标值
      :data-speed="25"
      :data-increment="1"
       :data-delay="0"/>

JS部分

const data = {
  config: {
    min: 0, //起始值
    max: 0, //目标值
    speed: 100, //滚动速度(ms)
    increment: 1, //滚动跨度
    delay: 0, //延迟滚动(ms)
  },
  attributes: {
    min: "data-min",
    max: "data-max",
    speed: "data-speed",
    increment: "data-increment",
    delay: "data-delay"
  }
};
class Screen {
  render(val) {
    this.element.innerHTML = val;
  }
}
export class Counter extends Screen {
  constructor(selector) {
    super();
    this.element = document.querySelector(selector);
    this.min = parseInt(this.element.getAttribute(data.attributes.min)) || data.config.min;
    this.max = parseInt(this.element.getAttribute(data.attributes.max)) || data.config.max;
    this.speed = parseInt(this.element.getAttribute(data.attributes.speed)) || data.config.speed;
    this.increment = parseInt(this.element.getAttribute(data.attributes.increment)) || data.config.increment;
    this.delay = parseInt(this.element.getAttribute(data.attributes.delay)) || data.config.delay;
    this.current = this.min;
    this.interval;
    this.initialize();
  }
  // 定时滚动数字
  initialize() {
    if (this.delay > 0) {
      setTimeout(() => {
        this.interval = setInterval(
          this.count.bind(this),
          this.speed
        );
      }, this.delay);
    } else {
      this.interval = setInterval(
        this.count.bind(this),
        this.speed
      );
    }
    this.render(this.min);
  }
  // 数字增加
  count() {
    if (this.current < this.max) {
      this.current += this.increment;
      this.render(this.current);
    } else if (this.current > this.max) {
      this.render(this.max);
      this.clearTime();
    }
  }
  // 清除定时器
  clearTime() {
    clearTimeout(this.interval);
    return;
  }
}

在组件中引入并调用 

import { Counter } from "XXX";  
 setTimeout(() => {
         new Counter(".delivery");
        }, 0);

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值