2010-11-25 159 views
3

我有大約20個不同的圖像,我想淡入和出4盒。我需要它隨機從圖像列表中選擇一個圖像並顯示它。多個圖像淡入/淡出

箱子示例photo1,photo2,photo3,photo4是他們的名字。他們需要單獨命名,因爲他們絕對定位。

<div id="photo1"> 
    <img src="images/photo.jpg" width="300" height="300" /> 
    <img src="images/photo2.jpg" width="300" height="300" /> 
    <img src="images/photo3.jpg" width="300" height="300" /> 
    <img src="images/photo4.jpg" width="300" height="300" /> 
    <img src="images/photo5.jpg" width="300" height="300" /> 
    </div> 

的jQuery到目前爲止

<script type="text/javascript"> 

//generate random number 
var randomnumber=Math.floor(Math.random()*$("#photo1").children().length); 
$(function() { 
    //hide all the images (if not already done) 
    $("#photo1 > img").hide(); 

    //set timeout for image to appear (set at 500ms) 
    setTimeout(function(){ 
     //fade in the random index of the image collection 
     $("#photo1 > img:eq(" + randomnumber + ")").fadeIn(); 
    }, 500);  
}); 
</script> 

回答

1

我重構代碼:

$(function() { 
    // match all divs with ID starting with 'photo' 
    $("div[id^=photo] > img").hide(); 
    setTimeout(function(){ 
     $("div[id^=photo]").each(function() { 
      var rand = Math.floor(Math.random() * $(this).children().length); 
      $(this).find('img:eq(' + rand + ')').fadeIn(); 
     }); 
    }, 500);  
}); 

http://api.jquery.com/attribute-starts-with-selector/