Photoswipe 在此实现中无法正确关闭 [使用 Slick Carousel]

Photoswipe does not close properly in this implementation [with Slick Carousel]

当 Slick 轮播中有多个图像时,关闭 Photoswipe 后似乎随机重现了一个问题。从视觉上看,效果是 Photoswipe 关闭(没有任何动画消失),然后页面右侧再次变为黑色,在 Photoswipe 中查看的最后一张照片可见,然后黑色背景逐渐变为透明但似乎仍然存在(它防止任何按钮都不会被点击)。

如果相关,Photoswipe 打开动画的行为也不像演示 - 它不会从缩略图放大,它只是从页面中心淡入。

出现问题后的页面图片:https://i.imgur.com/a4XEMxU.png

这是我同时使用 Slick 和 Photoswipe 的实现:

  var carousel = $('#sc');
  var pswpImages = [];
  var options = {
    history: false
  };
  var count = 0;
  for (var fn in data.images) {
    var pieces = fn.split('.');
    var fullsize = meta_data['media'] + fn;
    var thumbnail = meta_data['cache'] + pieces[0] + '_m.' + pieces[1];
    carousel.append('<div><img src="' + thumbnail + '" class="sc" data-id="' + count + '"></div>');
    count += 1;
    $('.sc').each(function () {
      $(this).on('click', function () {
        options.index = $(this).data('id');
        var pswpElement = document.querySelectorAll('.pswp')[0];
        var gallery = new PhotoSwipe(pswpElement, PhotoSwipeUI_Default, pswpImages, options);
        gallery.init();
      })
    });
    pswpImages.push({
      src: fullsize,
      msrc: thumbnail,
      w: data.images[fn]['x'],
      h: data.images[fn]['y']
    });
  }
  // TODO: When closing gallery, get image number, and slick.GoTo that slide
  carousel.slick({
    dots: true,
    infinite: true,
    speed: 300,
    slidesToShow: 1,
    variableWidth: true,
    centerMode: true
  });

你能提供一个fiddle吗?

我怀疑 $('.sc').each(function () 需要在 for 循环之外,否则你会为每个 img 创建一个点击事件之前由 for 循环创建。

第一次迭代:

  • 在那个 1 img
  • 上创建 1 div, .each( ..on('click'))

第二次迭代:

  • 在第一个和第二个 img
  • 上创建第二个 div、.each( ..on('click'))

..等等。

所以,最后:单击一个图像将启动 PhotoSwipe 的多个实例,但前提是图像超过 1 个 - 就像您观察到的那样。第一次迭代还是可以的。

一个简单的解决方法是在 .on() 之前调用 .off(),例如:

...
    $('.sc').each(function () {
      $(this).off().on('click', function () {
        options.index = $(this).data('id');
...