lightbox 2: how to add dynamically images via javascript

那年仲夏 提交于 2019-12-04 05:12:49

问题


I'm having trouble attempting to dynamically add images, since lightbox2 (by lokesh dakar) is initialized after document load by existent html coded images and it doesn't parse the document anymore after the first time.

If i try to add new images with javascript (appending them in the body for example) they are not added to the lighbox groups.

Documentation in official website doesn't seems to describe any scripted method

Anyone with experience can help me? solution with jquery are really welcome, but i can handle well vanilla js too.


Code sample:

HTML

<body>
 <div id="container">
  <a href="images/image-2.jpg" data-lightbox="roadtrip">Image #2</a>
  <a href="images/image-3.jpg" data-lightbox="roadtrip">Image #3</a>
  <a href="images/image-4.jpg" data-lightbox="roadtrip">Image #4</a>
 </div>
 <!-- where 'Image #X' = <img src="images/thumb/image-X.jpg>" -->
 <div id="loadmore">load more images</div>
 <script src="path/to/lightbox.js"></script>
 <script>
  /* see below for the script */
 </script>
</body>

javascript

$(function(){
  $('#loadmore').click(function(){
   //ajax request for more images.
   //load them with all the needed properties...
   //then put them into the container:
   var IMG = $('<a href="images/image-10.jpg" data-lightbox="roadtrip">'+
       '<img src="images/small/image-10.jpg">'+
     '</a>');
   //magic here... add IMG to roadtrip lightbox group!!!
   //probably something like lightbox.groups['roadtrip'].add(IMG)
   //but i'm only speculating
   $('#container').append(IMG)
  });
})

回答1:


After a couple of hours spent on testing and reading the code, I came up with this magic code:

//set album values
IMG = $('<a href="...">')
    .attr('data-lightbox','roadtrip')
    .append('<img src="...">')
//lightbox open:
IMG.click(function(){
    lightbox.start($(this));
    return false;
})

some helpful tips:

  • don't set data with $(...).data('lightbox','group'), since lightbox uses the selector $('a[data-lightbox]') each time a link is clicked. Instead, you should use $(...).attr('lightbox','group').

  • lightbox.album is a temporary variable which you don't need to deal with.




回答2:


To add existing img tags to be lightboxified on their own (without gallery functionality) one could use something like:

$('img')
    .wrap(function(index) {
        return '<a href="'+$(this).attr('src')+'" data-lightbox="image-'+index+'"></a>';
    });

Just add it BEFORE inserting the lightbox.js



来源:https://stackoverflow.com/questions/34454681/lightbox-2-how-to-add-dynamically-images-via-javascript

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