how do I trigger fancybox gallery with dynamic content

痞子三分冷 提交于 2019-12-23 16:06:03

问题


Im testing out fancybox, looks quite a nice little library for galleries and loading in content. I've got the following code below kind of working, however I need it to trigger off the gallery as soon as I click on an item with the lightbox class. The code below loads content from gallery.htm into the content div and then when I click on a thumbnail image from my content div it launces fancybox. What I am trying to do is on one click load my dynamic content and launch fancy box, anyone advise me please?

$(document).ready(function(){
$('.lightbox').live('click', function(e){
    e.preventDefault();
    //var url = $(this).attr('href');
    var url = "gallery.htm";
    $('#content').load(url, function(data, stat, req){
        $("a.lightbox").fancybox();
    });
})

});

Thank you


回答1:


Basically you would need two selectors:

1). one to load the gallery thumbnails into the page using the .load() method, e.g. loadGallery:

<a href="javascript:;" class="loadGallery">add dynamic gallery thumbnails</a>

2). another to bind elements to fancybox, e.g. lightbox. All the elements within the file "gallery.htm" should have then such class like:

<a class="lightbox" rel="gallery1" href="images/01.jpg"><img src="images/01t.jpg" alt="" /></a>
<a class="lightbox" rel="gallery1" href="images/02.jpg"><img src="images/02t.jpg" alt="" /></a>
<a class="lightbox" rel="gallery1" href="images/03.jpg"><img src="images/03t.jpg" alt="" /></a>

Then bind those elements (in your main page) to fancybox with one script and load the gallery thumbnails into the page and fire the fancybox gallery within the same click, with another like :

$(document).ready(function(){
 // bind elements to fancybox
 $(".lightbox").fancybox();
 // load thumbnails and fire fancybox gallery
 $('.loadGallery').on('click', function(e){
  e.preventDefault();
  var url = "gallery.htm";
  $('#content').load(url, function(data, stat, req){
   $(".lightbox").eq(0).trigger("click");
  }); // load
  $(this).remove(); // you may remove the selector loadGallery after loading the thumbnails
 }); // on
}); // ready

Notice that we are using .on() instead of .live() since the second has been deprecated. The .on() method requires jQuery 1.7+ though.

Also notice that we used .eq(0) to start the gallery from the first item, otherwise the gallery will start from the last element appended to the document.

UPDATE : See it working here DEMO




回答2:


I would make Aajax request which would return JSON response containing gallery items. Then I would open fancybox manually (e.g. $.fancybox.open( response ); where response would be like [{href: ''},{href:''}])



来源:https://stackoverflow.com/questions/10986953/how-do-i-trigger-fancybox-gallery-with-dynamic-content

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!