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);