简体   繁体   中英

Load clicked image only

I have a CSS lightbox gallery on my website, however it loaded the thumbnails and the large images at the same time.

Below are the contents of my various files;

HTML:

<div class=galerie>
<a href="#img1" class=galimg><img src=/images/thumbnail.jpg /></a><a href="#_" class=lightbox id="img1"><img data-src="/images/large-image.jpg"></a>
<a href="#img2" class=galimg><img src=/images/thumbnail.jpg /></a><a href="#_" class=lightbox id="img2"><img data-src="/images/large-image.jpg"></a>
<a href="#img3" class=galimg><img src=/images/thumbnail.jpg /></a><a href="#_" class=lightbox id="img3"><img data-src="/images/large-image.jpg"></a>
<a href="#img4" class=galimg><img src=/images/thumbnail.jpg /></a><a href="#_" class=lightbox id="img4"><img data-src="/images/large-image.jpg"></a>
</div>

CSS:

.lightbox{display:none;position:fixed;z-index:10001;width:100%;height:100%;text-align:center;top:0;left:0;background:black;background:rgba(0,0,0,0.8)}
.lightbox img{max-width:100%;max-height:100%}
.lightbox:target{display:block;outline:none}

I've added a script (jQuery):

<script>
    $("a.galimg").click(function() {
        $(".lightbox").each(function() {
            $(this).find("img").attr("src", $(this).find("img").attr("data-src"));
        });
    });
</script>

And now the large files are loaded only after I click a thumbnail.

The problem is that they all load at once, and I want only the clicked one to load at a time.

Is there a way to do this?

I know the each function does that, is there any other function I could use?

Attr sets an attribute, if you're trying to use it, I would go with something like this. I'm not sure what you're trying to set the attribute to, but this is the syntax:

<script>
$("a.galimg").click(function() {
        $(this).attr("data-src", "your desired data attribute");
    })
});
</script>

http://www.w3schools.com/jquery/html_attr.asp

I'm not sure why you want to do something like this (would be easier if you post a link to your site) but i'll try to help. Just don't use 'each' function. So your code should look something like this:

$("a.galimg").click(function() {
    var imgID = $(this).attr('href');
    $(imgID).attr("src", $(this).data('srcbig'));
});

And for HTML:

<div class=galerie>
    <a href="#img1" class="galimg" data-srcbig="/images/big-img-1.jpg"><img src=/images/thumbnail.jpg /></a><a href="#_" class=lightbox id="img1"><img src="" alt="remember about me"></a>
</div>

You could even delete the second 'a href' and image and just create it dynamically. It all depends on how your lightbox library works and what you need.

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