javascript - 如何在多个文本上添加计数器

标签 javascript html timer counter

我有一个多重饼图,里面有文本来显示百分比,我想为它设置动画。下面的代码递增,计数直到数量达到一百。

var text = document.querySelectorAll('text');
var duration = setInterval(count, 14);
var c = 0;
function count(){
    for (var i = 0; i < text.length; i++) {
       if(c == 101){
            clearInterval(time);
       }else {
           text[i].textContent = c + '%';
       }
    }
    c++;
}

但我想在每个项目上有不同的文本/数字。我尝试了下面的代码,但数字从 0 跳到我指定的值。

var text = document.querySelectorAll('text');
var duration = setInterval(count, 14);
var c = 0;
function count(){
    for (var i = 0; i < text.length; i++) {
       if(c == 82){
           text[0].textContent = c + '%';
       }else if(c == 46){
           text[1].textContent = c + '%';
       }else if(c == 76){
           text[2].textContent = c + '%';
       }else if(c == 56){
           text[3].textContent = c + '%';
       }else if(c == 26){
           text[4].textContent = c + '%';
       }else if(c == 96){
           text[5].textContent = c + '%';
       }
    }
    c++;

}
setInterval(count, 14);

最佳答案

您不需要声明,因为您手动访问所有元素并且您希望数字在其值小于目标时更改:

function count(){
       if(c <= 82)
           text[0].textContent = c + '%';
       if(c <= 46)
           text[1].textContent = c + '%';
       if(c <= 76)
           text[2].textContent = c + '%';
       if(c <= 56)
           text[3].textContent = c + '%';
       if(c <= 26)
           text[4].textContent = c + '%';

//after reaching to highest number you need to stop the clock

       if(c <= 96)
           text[5].textContent = c + '%'
       else 
           clearInterval(time);

    c++;
}

关于javascript - 如何在多个文本上添加计数器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53420755/

相关文章:

javascript - 如何在换幻灯片时暂停 youtube 视频?

javascript - 在javascript中调用函数的最佳方式

html - 尽管 for=id,但单击标签不会聚焦输入

html - 我如何访问 A Div 中的第一个表

javascript - 我怎样才能把这段代码变成一个jquery函数

javascript - HTML5 anchor 不工作

html - 如何: Non collapsing navigation items Bootstrap 3

javascript - 同步 Javascript 计时器

java - Swing 计时器未按计划工作

java - JPanel 中的计时器未启动