简体   繁体   中英

Add lightbox effect to images automatically

Is it possible to add a lightbox effect automatically to every image which is embedded like this

<img class="full-img" src="/blog/content/images/2014/Jun/biking_hwy1.jpg" alt="">

to this

<a href="/blog/content/images/2014/Jun/biking_hwy1.jpg" data-lightbox="how-to-enable-lightbox-in-ghost" data-title="This is my caption"><img class="full-img" src="/blog/content/images/2014/Jun/biking_hwy1.jpg" alt="" title=""></a>

after the page loaded successfully?

I would like to enable this on a Ghost CMS installation with JQuery support. Thanks in advance!

You could have Javascript on every image in the page and then alter the attributes as necessary. Not necessarily the best approach (doing it server-side is preferred), but it can work. You will also, most likely, need to re-instantiate the lightbox plugin to reparse the page after you go through the images.

var img = jQuery("img");

img.each(function() {
   var element = jQuery(this);
   var a = jQuery("<a />", {href: element.attr("src"), "data-lightbox": "test"});

   element.wrap(a);
});

http://jsfiddle.net/ak74A/1/

You'll need to add your own customized properties, but you get the idea.

additional to Jason idea, if you want to add lightbox to images without an anchor tag parent, we can add an if statement to check if the img parent is an anchor tag.

var img = jQuery("img");
        img.each(function() {
            var element = jQuery(this);
            if( this.parentElement.tagName != "A" ){
                var a = jQuery("<a />", {href: element.attr("src"), 'data-lightbox': 'Article image'});
                element.wrap(a);
            }
        });

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