gpt4 book ai didi

javascript - 用动画增加数量

转载 作者:行者123 更新时间:2023-11-30 11:50:13 26 4
gpt4 key购买 nike

我正在尝试增加页面上元素内的数字。但是我需要数字包含一个逗号,而增量只会每秒增加 1 位。

我的代码可以正常工作,但我不确定在哪里设置每秒仅增加 1 位的增量(例如:10,100,040 然后是 10,100,041 等等上)

<script></script>
<div id="el"></div>
// Animate the element's value from x to y:
$({
someValue: 40
}).animate({
someValue: 45000000
}, {
duration: 3000,
easing: 'swing', // can be anything
step: function() { // called on every step
// Update the element's text with rounded-up value:
$('#el').text(commaSeparateNumber(Math.round(this.someValue)));
},
complete: function(){
$('#el').text(commaSeparateNumber(Math.round(this.someValue)));
}
});

function commaSeparateNumber(val){
while (/(\d+)(\d{3})/.test(val.toString())){
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return "$" + val;
}

最佳答案

间隔会比 jQuery 的 animate() 方法更适合实现此目的,后者旨在修改 DOM。试试这个:

var start = 40, end = 45000000;
var interval = setInterval(function() {
var $el = $('#el');
var val = $el.data('value') || 40;
$el.text(commaSeparateNumber(++val)).data('value', val)

if (val >= end)
clearInterval(interval);
}, 1000);

function commaSeparateNumber(val) {
while (/(\d+)(\d{3})/.test(val.toString())) {
val = val.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");
}
return "$" + val;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="el">$40</div>

关于javascript - 用动画增加数量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39697148/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com