Javascript - having trouble with a function I wrote to fade images in
So I have written a function whose purpose is to fade an image from 0 opacity, to 1. It is meant to increase the opacity by 0.1 every 100ms, for a total duration of 1s. The function will call, and it will increase the opacity, but it seems to simply wait for 100ms and set the opacity to 1 straight away. Any ideas where I'm going wrong? Here are the code snippets r开发者_如何学运维elevant to the function and images that should be faded in. I appreciate any input =)
Javascript:
function setOpacity(id, num) {
document.getElementById(id).style.opacity = num;
}
function imagePopUp(id){
var step = 0.0;
for(var i = 1; i <= 10; i++){
step = i / 10;
var num = step.toFixed(1);
setTimeout(function(){setOpacity(id, num);}, 100);
}
}
HTML:
<div id ="shadowWrapper">
<div id ="imageContainer">
<img class ="sideImages" src ="images/mini_race1.jpg" onclick ="imagePopUp('image1')"></img>
<img class ="sideImages" src ="images/mini_race2.jpg" onclick ="imagePopUp('image2')"></img>
<img class ="sideImages" src ="images/mini_race3.jpg" onclick ="imagePopUp('image3')"></img>
</div>
<img class ="hiddenImages" id ="image1" src ="images/race_around_ireland_01.jpg"></img>
<img class ="hiddenImages" id ="image2" src ="images/race_around_ireland_02.jpg"></img>
<img class ="hiddenImages" id ="image3" src ="images/race_around_ireland_03.jpg"></img>
</div>
CSS:
#imageContainer {
position: absolute;
margin-top: 10px;
width: 200px;
height: 450px;
left: 600px;
}
.sideImages {
display: block;
width: 150px;
height: 112px;
border: 1px #94b62d solid;
margin-top: 20px;
margin-left: auto;
margin-right: auto;
}
.hiddenImages {
display: block;
position: absolute;
border: 1px black solid;
left: 100px;
opacity: 0.0;
}
You are queuing all of the callbacks to execute 100ms from now. setInterval
doesn't "stack" or "queue" functions.
Additionally, the same num
variable is getting captured in the closures you are creating, and it will have its final value when executed in each callback.
A fix for both issues would be to replace
setTimeout(function(){setOpacity(id, num);}, 100);
with
setTimeout(function(inum) {
return function(){setOpacity(id, inum);};
}(num), i * 100);
精彩评论