You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免同一张图片被重复添加到PhotoSwipe数组中?

解决PhotoSwipe数组中图片集首图重复的问题

你的问题出在遍历选择器的逻辑上——你同时选中了figure和.photoset-cell元素,但第一个article里的figure本身就包含了.photoset-cell,这导致第一张图片被两次加入到PhotoSwipe的数组中:一次是遍历外层figure时找到它,另一次是遍历内层.photoset-cell时又找到它。

修复方案:区分图片集和单图的遍历逻辑

我们需要调整遍历规则:对于包含图片集(.photoset-cell)的文章,只遍历里面的.photoset-cell;对于单图文章,遍历figure。这样就能避免重复收集图片。

修改后的jQuery代码如下:

'use strict'; 
/* global jQuery, PhotoSwipe, PhotoSwipeUI_Default, console */ 

(function($) { 
  // Init empty gallery array 
  var container = []; 
  // 先构建统一的元素集合:图片集取cell,单图取figure
  var $galleryItems = $('article').map(function() {
    var $article = $(this);
    if ($article.find('.photoset-cell').length) {
      // 图片集:返回所有cell元素
      return $article.find('.photoset-cell').get();
    } else {
      // 单图:返回figure元素
      return $article.find('figure').get();
    }
  }).get();

  // 遍历统一集合,填充图片数组
  $($galleryItems).each(function() { 
    var $link = $(this).find('img, video'), 
        item = { 
          src: $link.attr('src'), 
          w: $link.data('width'), 
          h: $link.data('height'), 
        }; 
    container.push(item); 
  });

  // Define click event on gallery item 
  $('img, video').click(function(event) { 
    // Prevent location change 
    event.preventDefault(); 
    // 计算当前点击元素对应的集合索引
    var currentItem = $(this).closest('.photoset-cell, figure');
    var itemIndex = $galleryItems.indexOf(currentItem.get(0));

    // Define object and gallery options 
    var $pswp = $('.pswp')[0], 
        options = { 
          index: itemIndex, 
          bgOpacity: 0.9, 
          showHideOpacity: true, 
        }; 

    // Initialize PhotoSwipe 
    var gallery = new PhotoSwipe($pswp, PhotoSwipeUI_Default, container, options); 
    gallery.init(); 
  }); 
}(jQuery));

关键修改点:

  • 统一元素集合:用map方法构建$galleryItems,确保每个图片只对应一个元素(要么是.photoset-cell,要么是figure),不会重复。
  • 遍历逻辑优化:基于统一集合遍历,避免重复收集同一张图片。
  • 索引计算修正:通过indexOf获取当前元素在统一集合中的位置,保证PhotoSwipe打开时显示正确的图片。

这样修改后,图片集的首图就不会再被重复添加到数组里,所有功能也能正常运行。

内容的提问来源于stack exchange,提问作者MDLR

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.27 04:26:45