悬停时显示阵列中的所有图像

display all images in an array upon hover over

本文关键字:图像 显示 阵列 悬停      更新时间:2023-09-26

当有人悬停在Class of 2013上时,我想显示(淡入)数组中的所有图像。

到目前为止,我可以在悬停时显示一张图像。。。

我可以将它们全部发送到同一个<img src...吗?

问题是,我有三个班——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>

为了方便起见,我会将所有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);
    });
});

我为你编辑了一个非常简单的例子:

工作示例