javascript用较大的图像交换缩略图

javascript swap thumbnail with larger image

本文关键字:交换 略图 图像 javascript      更新时间:2023-09-26

我对网络编程很陌生,现在正在网站上工作。在这个网站的一部分,我收集了3张图片。1个较大的缩略图和下面的两个较小的缩略图。目标是创建一种方式,我可以点击其中一个缩略图,它们可以用一张大图交换位置。你知道我该怎么做吗?这是一段代码。谢谢

<div class = 'picture-container'>
            <div class = 'large-picture' id = 'lp1'>
                <figure style = 'float:left;width:45%;'>
                    <img src = 'close_table_dupontstudios.png' width = '100%' height = '100%' class = 'no-mobile'>
                    <figcaption class = 'red-cap'>Our Set-Up</figcaption>
                </figure>
                <div class = 'picture-content'>
                    <div class = 'picture-title'>BOUTIQUE PRODUCTION STUDIO</div>
                    <div class = 'picture-text'>We built a boutique full service production studio that allows for one, two and three person filmed interviews and conversations. We have studio lights, a three camera set-up and remote monitoring. Additionally, our Infinity Wall creates a clean and professional look that allows the film to be about the message.</div>
                    <!--<div class = 'small-picture'>
                        <img src = 'hair_and_makeup_dupontstudios.png' width = '175' height = '100'>
                    </div>
                    <div class = 'small-picture'>
                        <img src = 'infinity_wall_dupontstudios.png' width = '175' height = '100'>
                    </div>-->
                </div>
                <div class = 'thumbnail-container'>
                    <figure class = 'thumbnail'>
                        <img src = 'infinity_wall_dupontstudios.png' width = '100%' height = '100%'>
                    </figure>
                    <figure class = 'thumbnail'>
                        <img src = 'infinity_wall_dupontstudios.png' width = '100%' height = '100%'>
                    </figure>
                </div>
            </div>
        </div>

有很多方法可以解决这个问题。最简单的方法是转储所有图像(大图像和小图像),一次只显示一个。

因此,在源代码中,除了第一个图像之外,所有的大图像都将有一个hidden类,这使它们成为display: none。然后,当点击缩略图时,只需要显示正确的大图像。

要显示正确的大图像,您需要通过标识符将缩略图与大图像相关联。以下是将缩略图链接的href设置为大图像id的示例。

<a href="#lp1">
  <figure class="thumbnail">...</figure>
</a>

现在添加javascript(jQuery)。

// preselect all large images
var largeImages = $('figure.large');
// add handler for thumbnail clicks
$('.thumbnail-container').on('click', 'a', function (e) {
    e.preventDefault();
    var thumbnailLink = $(this),
        selectedLarge = $(thumbnailLink.attr('href'));
    // hide all the large images
    largeImages.addClass('hidden');
    // show the large image that corresponds to the clicked thumbnail
    selectedLarge .removeClass('hidden');
});

所以,最简单的方法是隐藏/显示,但这种方法并不是最有效的。它使客户端加载所有图像,即使它们是隐藏的。

一种更有效的方法是在缩略图中添加data-属性,并且在缩略图点击处理程序内部使用来自点击缩略图的数据更新大的内容区域。要"替换"图像,只需要替换src属性。