2013-07-23 32 views
-2

我想要顯示(淡入)陣列中的所有圖像時,有人懸停在Class of 2013顯示在懸停陣列中的所有圖像上

到目前爲止,我能夠在懸停顯示一個圖像...

我可以他們都發送到同一個<img src...

事情是,我有3個類,2013, 2014, 2015 ...和每個圖像路徑陣列是不同的長度...所以我想動態地輸入正確數量的img src元素來顯示給定的數量每班的圖像。

這裏是我當前的代碼:

<html> 
<head> 
    <script src="jquery.js"></script> 

    <script type="text/javascript">  
     var ITLP = new Array(); 
     ITLP[0] = "./name1.jpg"; 
     ITLP[1] = "./name2.jpg"; 
     var max = ITLP.length; 

     $(document).ready(function() { 
      showimg();   
     }); 


    function showimg() 
     { 
      $(".box > .overlay > img").attr("src",getImages()); 

      $(".box").hover(
       function(){ $(this).find(".overlay").fadeIn(); } , 
       function(){ $(this).find(".overlay").fadeOut(); } 
      );   
     } 
    function getImages() 
    {  
     console.log(max); 
     var i = Math.floor(Math.random()*max);  
     console.log(ITLP[i]); 
     return ITLP[i];    
    } 
    </script> 


</head> 
<body>    
    <div class="box"> 
     Class of 2013: 
     <div class="overlay"> <!-- Put ITLP images to display here...-->     
      <img src="" border="none"/>    
     </div> 
    </div>​ 

</body> 
</html> 

回答

2

我將所有的classes陣列,存儲的對象爲方便起見,像這樣:

var classes = { 
    2011: [ 
    'image1.jpg', 
    'image2.jpg', 
    'image3.jpg'], 
    2012: [ 
    'image4.jpg' 
    'image5.jpg'], 
    2013: [ 
    'image6.jpg'] 
}; 

然後,把對今年你的信息想要使用屬性在DOM元素內部顯示。您可以使用iddata-attribute

然後,JavaScript代碼會是這個樣子:

$(element).on('mouseover', function(e){ 

    // First, empty the overlay element to avoid images 
    // to be added over and over again. 
    $('#overlay').empty(); 

    // Let's dynamically change the title accessing the 
    // data stored in our element (I assumed it was id) 
    var title = $('<h2>'); 
    title.text('Class of ' + e.target.id); 
    $('#overlay').append(title); 

    // Loop through the target array and add an image tag 
    // for each element of your images array. 
    $(classes[e.target.id]).each(function(idx, entry){ 
     var img = $('<img/>'); 
     img.attr('src', entry); 
     $('#overlay').append(img); 
    }); 

}); 

我已經編輯爲你一個很簡單的例子:

Working example