0

请帮我将此 JQuery 转换为 Javascript 进度条脚本

var generateButton = document.getElementById("generate");

if (generateButton.addEventListener) {
   generateButton.addEventListener("click", random, false);
}
else if (generateButton.attachEvent) {
   generateButton.attachEvent('onclick', random);
} 

function random(e) {
 setTimeout(function(){

    $('.progress .bar').each(function() {
        var me = $(this);
        var perc = me.attr("data-percentage");

        //TODO: left and right text handling

        var current_perc = 0;

        var progress = setInterval(function() {
            if (current_perc>=perc) {
                clearInterval(progress);
            } else {
                current_perc +=1;
                me.css('width', (current_perc)+'%');
            }

            me.text((current_perc)+'%');

        }, 50);

    });

},300);

var num = Math.random();

var greetingString = num;
document.getElementById("rslt").innerText = greetingString;
}

这是现场版:http: //jsfiddle.net/chjjK/9/

4

1 回答 1

1

实际上很容易,使用document.getElementsByClassName一个for循环来替换每个:

var bar = document.getElementsByClassName("bar");
    for (var i = 0; i < bar.length; i++) {
        var me = bar[i];
        var perc = me.getAttribute("data-percentage");
        var current_perc = 0;

        var progress = setInterval(function() {
            if (current_perc>=perc) {
                clearInterval(progress);
            } else {
                current_perc +=1;
                me.style.width = current_perc+'%';
            }

            me.innerHTML = ((current_perc)+'%');

        }, 50);
    }
}, 300);

演示:http: //jsfiddle.net/chjjK/13/

于 2013-11-06T14:14:18.003 回答