-2

I'd like to display (fade in) all images in an array when someone hovers over Class of 2013.

So far, I'm able to display one image upon hover over...

Can I send them all to the same <img src...?

The thing is, I have 3 classes- 2013, 2014, 2015... and each array of image paths is a different length... so I'd like to dynamically put in the correct number of img src elements to display the given amount of images per class.

Here is my current code:

<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>
4

1 回答 1

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

于 2013-07-23T17:07:48.663 回答