简体   繁体   中英

Clicking a thumbnail to change the large image in a gallery

I'm trying to create the following gallery:
- One large image
- Thumbnails of gallery images below
- Large image should open all images on click in a lightbox gallery

I have the lightbox gallery working using PhotoSwipe and it fires when I click the large image. I also have the thumbnails in place below the large image. My question now is how do I change the large image when I click one of the thumbnails? I've seen a lot of examples (also quite simple ones), but none of them seem to work in my case.

Here's the code that I have for the thumbnail:

<a href="<?php echo $image['url']?>" data-size="<?php echo $image['width']?>x<?php echo $image['height']?>" data-index="0">
  <img src="<?php echo $image['url']?>">
</a>

What I want is that when I click the href of the thumbnail that it changes the big image, which is display with this code:

<img class="bigimg" src="imageurl.jpg">

The thumbnail needs to have the href tag because this is required for the lightbox function to work.

I've seen some jQuery examples that replace the src of the bigimg with the src of the thumbnail, but I can't quite get it to work with the href also in place.

For reference, this is the situation.

Example: JSFiddle

I'm not intimately familiar with lightbox, but if I understand you correctly, you want it to just do what it's already doing, but in addition, change the src of your img.bigimg . If that's the case, it should work to add your own listener on the a tag as long as you don't prevent the default action. Something along the lines of this:

var thumbnailLinks = $('a.thumbnailLink') // Add class="thumbnailLink" where appropriate or use a different selector.
thumbnailLinks.on('click', function() {
    $('img.bigimg').attr('src', $(this).attr('href')); // Set img.bigimg src attribute to the href attribute of the link that was clicked.
});

There may be some weaknesses to this. For example I'm not sure if this will work if a user tabs through links and activates it using the enter key, though it should be possible to add other events than just click to help with that. This is also untested code at the moment, but have a go and see if it works for you.

Try,

var thumbnailLinks = $('a.thumbnailLink') // Add class="thumbnailLink" where appropriate or use a different selector.
$('.thumbnailLink').click(function() {
  $('.big a').attr('href', $(this).attr('href'));
  $('.bigimg').attr('src', $(this).attr('href')); 
});

here is the fiddle https://jsfiddle.net/91oq8ja2/2/

Is this what you are looking for?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM