How to set group for images without link in Fancyb

2019-08-05 08:33发布

问题:

Currently I use this code for apply Fancybox to a set of images not wrapped by tag <A>:

$("img[alt=lightbox]").each(function(){
   $(this).fancybox({ href : $(this).attr('src') });
});

Now I'd like to add to the same group all images added in this way.

I tried with:

$("img[alt=lightbox]").each(function(){
   $(this).attr("data-fancybox-group", "gallery");
   $(this).fancybox({ href : $(this).attr('src') });
});

Without luck, do you have any advice?

回答1:

The answer for this question Fancybox gallery without a href? was written for fancybox v1.3.4.

The same solution would work equally for fancybox v2.x, however bear in mind that fancybox v2.x API options are new and not compatible with previous versions ... so you have actually to upgrade the API options to make it work with v2.x

Here is the v2.x update :

The basic html :

 <div id="myContainer">
  <img src="images/01t.jpg" data-href="images/01.jpg" alt=""  />
  <img src="images/02t.jpg" data-href="images/02.jpg" alt=""  />
  <img src="images/03t.jpg" data-href="images/03.jpg" alt=""  />
  <img src="images/04t.jpg" data-href="images/04.jpg" alt=""  />
  <img src="images/05t.jpg" data-href="images/05.jpg" alt=""  />
 </div>

... notice that we used the (HTML5) data-* (data-href) attribute to target the big images and let the src attribute to target the thumbnails.

Then the js :

// the function we call when we click on each img tag
function fancyBoxMe(e) {
    var numElemets = $("#myContainer img").size();
    if ((e + 1) == numElemets) {
        nexT = 0
    } else {
        nexT = e + 1
    }
    if (e == 0) {
        preV = (numElemets - 1)
    } else {
        preV = e - 1
    }
    var tarGet = $('#myContainer img').eq(e).data('href');
    $.fancybox({
        href: tarGet,
        helpers: {
            title: {
                type: 'inside'
            }
        },
        afterLoad: function () {
            this.title = 'Image ' + (e + 1) + ' of ' + numElemets + ' :: <a href="javascript:;" onclick="fancyBoxMe(' + preV + ')">prev</a>&nbsp;&nbsp;&nbsp;<a href="javascript:;" onclick="fancyBoxMe(' + nexT + ')">next</a>'
        }
    }); // fancybox
} // fancyBoxMe

// bind click to each img tag 
$(document).ready(function () {
    $("#myContainer img").each(function (i) {
        $(this).bind('click', function () {
            fancyBoxMe(i);
        }); //bind      
    }); //each
}); // ready

And of course, here is the DEMO



回答2:

According to fancy box:

Note - Galleries are created from elements who have the same "rel" tag, example:

Look at bottom of page here

So try setting the rel:

$("img[alt=lightbox]").each(function(){
  $(this).attr("rel", "gallery");
  $(this).fancybox({ href : $(this).attr('src') });
});