1

我正在尝试根据上传进度更改元素背景颜色。我遇到的问题是,与触发的进度事件侦听器相比,for 循环速度较慢。对此我能做些什么吗?

var colors = [
    "#fff2f2",
"#ffe6e6",
"#ffd9d9",
"#ffcccc",
"#ffbfbf",
"#ffb3b3",
"#ff9999",
"#ff7373",
"#ff8080",
"#ff5959",
"#ff4d4d",
"#ff4040",
"#ff3333",
"#ff2626",
"#ff1919",
"#ff0d0d",
"#ff0000",
]

var first = 0;
var last = 5;
var xhr = new XMLHttpRequest();

xhr.upload.addEventListener("progress", updateProgress, false);

var foo = document.getElementById("uploadScreen");
var form = document.getElementById("uploadForm");
var percentComplete;

xhr.open("POST", "php/upload.php", true);
xhr.send(new FormData(form));

function updateProgress(event) {
    if (event.lengthComputable) {
        percentComplete = Math.round(event.loaded / event.total * 100);
        for (i=0; i < colors.length; i++) {
            if (percentComplete > first && percentComplete < last ) {
                console.log(foo.style.backgroundColor = colors[i]);
                break;
            }
        }
        first = first +5;
        last = last +5;
    } else {
        alert("no no");
    }
}
4

2 回答 2

1

与其将整数作为百分比,不如将其保留为 0 到 1 之间的值。然后将其乘以数组的长度即可获得正确的索引。

var percentComplete = event.loaded / event.total;
var index = Math.round(percentComplete * (colors.length - 1)); // Subtract 1 to account for zero based indexing
foo.style.backgroundColor = colors[index];

http://jsfiddle.net/h6bsU/

于 2012-11-09T03:04:42.667 回答
0
var colors = [
    "#fff2f2",
"#ffe6e6",
"#ffd9d9",
"#ffcccc",
"#ffbfbf",
"#ffb3b3",
"#ff9999",
"#ff7373",
"#ff8080",
"#ff5959",
"#ff4d4d",
"#ff4040",
"#ff3333",
"#ff2626",
"#ff1919",
"#ff0d0d",
"#ff0000",
]

var first = 0;
var last = 5;
var xhr = new XMLHttpRequest();

xhr.upload.addEventListener("progress", updateProgress, false);

var foo = document.getElementById("uploadScreen");
var form = document.getElementById("uploadForm");
var percentComplete;

xhr.open("POST", "php/upload.php", true);
xhr.send(new FormData(form));

function updateProgress(event) {
    if (event.lengthComputable) {
        percentComplete = Math.round(event.loaded / event.total * 100);
        var i=praseInt(percentComplete/5);
        console.log(foo.style.backgroundColor = colors[i]);
    } else {
        alert("no no");
    }
}

我认为在这种情况下不需要使用 for 循环。

于 2012-11-09T03:10:25.840 回答