1.实现背景
上周在一个完成任务领取红包的活动需求中,需要实现一个用户点击按钮弹出领取红包弹窗后,在关 闭弹窗返回原来的页面时,页面余额数字部分要展示一个每一位数字滚动后的效果。
因为之前没做过这样的效果,一开始也不知道要如何实现,本来想在GitHub
上找一下相关的库,看到一个最高star的库,但发现它是依赖jQuery
的,而且不可以npm
包引入。感觉就很没有必要,本来项目是react
框架的,就是要尽量少的操作DOM,为了解决这个滚动就要引入jQuery
,感觉不太合适。所以我决定还是自己实现,先看了一下别人的思路,然后自己再去实现。
2.实现思路
其实就是将传入的带滚动的n位数字拆分成每一个要滚动的数,然后动态的创建装着滚动到每一位相应数字的容器,然后放入传入的目标容器中。滚动到每一位相应的数字的实现可以通过动态创建从0到相应数字的间隔数的div
,div的内容分别为对应的数字,就像一个竖直写着从0-n的长纸条,然后拉着它在指定时间内从0上拉到目标数字。
3.实现过程
既然要封装,还是写成class
的形式吧,话不多说,直接上代码吧
- /**
- * 实现数字滚动的效果的类
- */
- class DigitScroll {
- constructor(options) {
- //获取容器的DOM,没有则抛出错误
- this.container = document.querySelector(options.container);
- if (!this.container) {
- throw Error("no container");
- }
- this.container.style.overflow = "hidden";
- this.container.style.display = "flex";
- //可视容器高度 也是滚动间隔距离,容器要设置高度,否则默认30px
- this.rollHeight = parseInt(getComputedStyle(this.container).height) || 30;
- this.container.style.height = this.rollHeight + "px";
- }
- roll(num) {
- // 将传入的要滚动的数字拆分后初始化每一位数字的容器
- this.initDigitEle(num);
- const numEles = this.container.querySelectorAll(".single-num");
- // 遍历生成每一位数字的滚动队列,如滚动到7,则生成内容为0,1,2,3,4,5,6,7的7个div,用于滚动动画
- [...numEles].forEach((numEle, index) => {
- const curNum = 0;
- let targetNum = Number(this.numberArr[index]);
- if (curNum >= targetNum) {
- targetNum = targetNum + 10;
- }
- let cirNum = curNum;
- // 文档碎片,拼凑好后一次性插入节点中
- const fragment = document.createDocumentFragment();
- // 生成从0到目标数字对应的div
- while (targetNum >= cirNum) {
- const ele = document.createElement("div");
- ele.innerHTML = cirNum % 10;
- cirNum++;
- fragment.appendChild(ele);
- }
- numEle.innerHTML = "";
- numEle.appendChild(fragment);
- //重置位置
- numEle.style.cssText +=
- "-webkit-transition-duration:0s;-webkit-transform:translateY(0)";
- setTimeout(() => {
- numEle.style.cssText += `-webkit-transition-duration:1s;-webkit-transform:translateY(${
- -(targetNum - curNum) * this.rollHeight
- }px);`;
- }, 50);
- });
- }
- // 初始化容器
- initDigitEle(num) {
- // 数字拆分位数
- const numArr = num.toString().split("");
- // 文档碎片,拼凑好后一次性插入节点中
- const fragment = document.createDocumentFragment();
- numArr.forEach((item) => {
- const el = document.createElement("div");
- // 数字是要滚动的,非数字如.是不滚动的
- if (/[0-9]/.test(item)) {
- el.className = "single-num";
- el.style.height = this.rollHeight + "px";
- el.style.lineHeight = this.rollHeight + "px";
- } else {
- el.innerHTML = item;
- el.className = "no-move";
- el.style.verticalAlign = "bottom";
- }
- // el.style.float='left';
- fragment.appendChild(el);
- }, []);
- this.container.innerHTML = "";
- this.container.appendChild(fragment);
- // 存储滚动的数字
- this.numberArr = numArr.filter((item) => /[0-9]/.test(item));
- }
- }
到此这篇关于JavaScript实现余额数字滚动效果的文章就介绍到这了,更多相关JavaScript实现 数字滚动 内容请搜索w3xue以前的文章或继续浏览下面的相关文章希望大家以后多多支持w3xue!