前端(javaScript)写数字滚动增长效果
直接贴代码!
js部分
//数字自增到某一值动画参数(目标元素ID,自定义配置)
function NumAutoPlusAnimation(targetEle, options) {
/*可以自己改造下传入的参数,按照自己的需求和喜好封装该函数*/
//不传配置就把它绑定在相应html元素的data-xxxx属性上吧
options = options || {};
var elementNode = document.getElementById(targetEle),
time = options.time || elementNode.dataset.time || 0, //总时间--毫秒为单位
finalNum = options.num || elementNode.dataset.num || 0, //要显示的真实数值
regulator = options.regulator || elementNode.dataset.regulator || 76, //调速器,改变 regulator的数值可以调节数字改变的速度
step = finalNum / (time / regulator),
/*每30ms增加的数值--*/
count = 0, //计数器
initial = 0;
var timer = setInterval(function () {
count = count + step;
if (count >= finalNum) {
clearInterval(timer);
count = finalNum;
}
//t未发生改变的话就直接返回
//避免调用text函数,提高DOM性能
var t = Math.floor(count);
if (t === initial) return;
initial = t;
// 每三位加一个 ,
function toThousands(num) {
return (num || 0).toString().replace(/(\d)(?=(?:\d{3})+$)/g, '$1,');
}
elementNode.innerHTML = toThousands(bigNumberTransform(initial));
}, 30);
};
// 大数字转换成千,万,百万,
function bigNumberTransform(value) {
const newValue = ['', '', '']
let fr = 1000
let num = 3
let text1 = ''
let fm = 1
while (value / fr >= 1) {
fr *= 10
num += 1
}
if (num <= 4) { // 千
// newValue[0] = Math.round(value/1000 )
newValue[0] = value
// newValue[1] = '千' // 千不显示文字 正常显示
} else if (num <= 8) { // 万
text1 = Math.round(num - 4) / 3 > 1 ? '千万' : ''
// text1 = Math.round(num - 4) / 3 > 1 ? '千万' : '万' // 万以上就显示文字万
// tslint:disable-next-line:no-shadowed-variable
fm = text1 === '千万' ? 10000000 :1
// fm = text1 === '万' ? 10000 : 10000000 // 万以上就显示文字万 需要处理尾文字
if (value % fm === 0) {
newValue[0] = Math.round(value / fm) + ''
} else {
newValue[0] = Math.round(value / fm).toFixed(0) + ''
}
newValue[1] = text1
} else if (num <= 16) { // 亿
text1 = (num - 8) / 3 > 1 ? '千亿' : '亿'
text1 = (num - 8) / 4 > 1 ? '万亿' : text1
text1 = (num - 8) / 7 > 1 ? '千万亿' : text1
// tslint:disable-next-line:no-shadowed-variable
fm = 1
if (text1 === '亿') {
fm = 100000000
} else if (text1 === '千亿') {
fm = 100000000000
} else if (text1 === '万亿') {
fm = 1000000000000
} else if (text1 === '千万亿') {
fm = 1000000000000000
}
if (value % fm === 0) {
newValue[0] = Math.round(value / fm) + ''
} else {
newValue[0] = Math.round(value / fm).toFixed(0) + ''
}
newValue[1] = text1
}
if (value < 1000) {
newValue[0] = value + ''
newValue[1] = ''
}
return newValue.join('')
}
//调用函数 并且把相关参数传进去
NumAutoPlusAnimation('changeNum',{
time :2000,
num :1024,
regulator :55
})
html 部分
<div id="changeNum"></div>