Как я могу получить большое всплывающее окно для отображения изображений и видео iframe в одной динамической галерее?

Я использую всплывающее окно Magnific для создания галереи изображений с помощью следующего:

$('.main-content').magnificPopup({
  delegate: '.gallery', // child items selector, by clicking on it popup will open
  type: 'image',
  gallery: {enabled:true}
  // other options
});

У меня также есть встроенное видео, используя следующее:

$('.video').magnificPopup({
    type: 'iframe',
    iframe: {
      markup: '<div class="mfp-iframe-scaler">'+
                '<div class="mfp-close"></div>'+
                '<iframe class="mfp-iframe" frameborder="0" allowfullscreen></iframe>'+
              '</div>', // HTML markup of popup, `mfp-close` will be replaced by the close button

      patterns: {
        youtube: {
          index: 'youtube.com/', // String that detects type of video (in this case YouTube). Simply via url.indexOf(index).

          id: 'v=', // String that splits URL in a two parts, second part should be %id%
          // Or null - full URL will be returned
          // Or a function that should return %id%, for example:
          // id: function(url) { return 'parsed id'; } 

          src: '//www.youtube.com/embed/%id%?autoplay=1' // URL that will be set as a source for iframe. 
        },
        vimeo: {
          index: 'vimeo.com/',
          id: '/',
          src: '//player.vimeo.com/video/%id%?autoplay=1'
        },
        gmaps: {
          index: '//maps.google.',
          src: '%id%&output=embed'
        }

        // you may add here more sources

      },

      srcAction: 'iframe_src', // Templating object key. First part defines CSS selector, second attribute. "iframe_src" means: find "iframe" and set attribute "src".
    }

});

Как я могу объединить видео iframe в галерею? Я не могу использовать массив элементов, потому что мои изображения и видео являются динамическими.

Спасибо


person user3398457    schedule 01.04.2014    source источник


Ответы (4)


Вот простое решение, которое я использовал для этого:

$('.image-link, .video-link').magnificPopup({
    callbacks: {
      elementParse: function(item) {
         // the class name
         if(item.el.context.className == 'video-link') {
           item.type = 'iframe';
         } else {
           item.type = 'image';
         }
      }
    },
    gallery:{enabled:true},
    type: 'image',
});

Он должен работать с форматировщиками типов.

person Alyssa Muu    schedule 21.06.2016
comment
У меня есть несколько классов на элементе. if(item.el.context.classList.contains('video-link')) { item.type = 'iframe'; } else { item.type = 'image'; } у меня работает - person Arnis Juraga; 08.09.2019

Вы можете определить тип элемента галереи, используя класс mfp-TYPE CSS. Таким образом, в этом случае вы должны добавить mfp-iframe к тегу привязки, указывающему на ваше видео, а плагин сделает все остальное.

HTML:

<div class="gallery">
  <!-- Image -->
  <a href="https://www.example.com/image-fullsize-1.jpg">
     <img src="https://www.example.com/image-thumbnail-1.jpg" alt="">
  </a>

  <!-- Video item with mfp-iframe class -->
  <a href="https://www.example.com/video-url" class="mfp-iframe">
     <img src="https://www.example.com/video-thumbnail.jpg" alt="">
  </a>

  <!-- Image -->
  <a href="https://www.example.com/image-fullsize-2.jpg">
     <img src="https://www.example.com/image-thumbnail-2.jpg" alt="">
  </a>

  <!-- Image -->
  <a href="https://www.example.com/image-fullsize-3.jpg">
     <img src="https://www.example.com/image-thumbnail-3.jpg" alt="">
  </a>
</div>

JS:

$('.gallery').magnificPopup(
        {
            delegate: 'a',
            type: 'image',
            tLoading: 'Loading image #%curr%...',
            mainClass: 'mfp-img-mobile',
            gallery: {
                enabled: true,
                navigateByImgClick: true,
                preload: [0,1] // Will preload 0 - before current, and 1 after the current image
            },
            image: {
                tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
                titleSrc: function(item) {
                    return '';
                }
            }
        }
    );

Более подробную информацию можно найти в документации:

http://dimsemenov.com/plugins/magnific-popup/documentation.html#content-types

person jazibobs    schedule 09.05.2017

Я решил эту проблему следующим образом.

$('.video').each(function(){

var items = [];
var temp_count = 0;

$('.img_container a').each(function(){
    if($(this).attr('class') == 'video'){
        items.push({
            src:$(this).attr('href'),
            type:'iframe'
        });
        temp_count = temp_count +1;
    }else{
        items.push({
            src:$(this).attr('href'),
            type:'image',
            tLoading: '', 
            removalDelay: 500
        });
        temp_count = temp_count +1;
    }

});

$('.img_container a').each(function(index2, element){    
    $(this).magnificPopup({
        items:items,
        midClick:true,
        index: parseInt(index2),
        gallery: {
            enabled: true
        }
    }); 
});
});

$('.magnific-gallery').each(function(index1, element){// .magnific-gallery = //.gallary var items = []; var temp_count = 0;

$('.img_container a').each(function(){
    if($(this).attr('class') == 'video'){
        items.push({
            src:$(this).attr('href'),
            type:'iframe'
        });
        temp_count = temp_count +1;
    }else{
        items.push({
            src:$(this).attr('href'),
            type:'image',
            tLoading: '', 
            removalDelay: 500
        });
        temp_count = temp_count +1;
    }
});



$('.img_container a').each(function(index1, element){   
    $(this).magnificPopup({`enter code here`
        items:items,
        midClick:true,
        index: parseInt(index1),
    //  index: 4,
        gallery: {
            enabled: true
        }
    }); 
});

});

Я надеюсь, что вы справитесь со своими проблемами на основе приведенного выше кода.

person John Smith    schedule 27.05.2015

    /*reference : https://gist.github.com/hirejordansmith/1ac659aadc1d720f505b28a1540d6547#file-magnific-popup-gallery-image-plus-video-js */
 $(".popup-youtube").removeAttr('class').attr('class','popup-youtube');
    $('.popup-gallery').magnificPopup({
      delegate: 'a',
      type: 'image',
      tLoading: 'Loading image #%curr%...',
      mainClass: 'mfp-img-mobile',
      gallery: {
        enabled: true,
        navigateByImgClick: true,
        preload: [0,1] // Will preload 0 - before current, and 1 after the current image
      },
      image: {
        tError: '<a href="%url%">The image #%curr%</a> could not be loaded.',
        /*titleSrc: function(item) {
          return item.el.attr('title') + '<small>by Marsel Van Oosten</small>';
        }*/
      },
      callbacks: {
        elementParse: function(item) {
     // the class name

     if(item.el.context.className == 'popup-youtube') {
       item.type = 'iframe';
     } else {
       item.type = 'image';
     }
        }
      },
  });

Полный рабочий пример, просто скопируйте и запустите код (измените имя класса в соответствии с вашим кодом).

person Anup    schedule 24.10.2017