简体   繁体   English

如何在一个阵列中加载多张要褪色的图像?

[英]How can I load multiple images in one array to be faded?

I have the following code which suppose to load couple of images and then to fade them. 我有以下代码,它们假设要加载几张图像然后使其褪色。 But instead to load all images on each fade it loads the same image every time. 但是,要在每次淡入淡出时加载所有图像,而是每次都加载相同图像。 Does anyone have any idea? 有人有什么主意吗?

http://jsfiddle.net/7kacz43o/8/ http://jsfiddle.net/7kacz43o/8/

var img, i,
    imageCount = [1,2,3,4],
    div = document.getElementById('foo');
console.log(imageCount.length);
for(i = 1; i <= imageCount.length; i++){
    img = new Image();
    img.onload = function() {
        div.appendChild(img);
    };
    img.src = 'http://tdhdemo.com/frames/frame_' + i + '.jpg';
    img.id = "top";
}

You reuse img inside onload , which means when the for runs for the next index, img will be overwritten. 您可以在onload重用img ,这意味着当for运行下一个索引时, img将被覆盖。 In the onload event only the last img will be appended to the div (4 times, but that results in one image tag). onload事件中,仅将最后一个img附加到div(4次,但结果是一个图像标签)。

Since you attach the onload function on the img itself, you can use this to reference the image: 由于您在img本身上附加了onload函数,因此可以使用this来引用图像:

img.onload = function() {
    div.appendChild(this);
};

Another recommendation: Instead of using an array and its length to power your for loop, why not use a count variable directly? 另一个建议:为什么不使用数组及其length来驱动for循环,为什么不直接使用count变量呢?

var imageCount = 4;
...
for (i = 1; i <= imageCount; i++) {

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM