[英]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.