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

使用JavaScript动态调整Squarespace画廊容器适配单张图片宽高

解决Squarespace幻灯片画廊字幕间距不一致的问题

核心思路

既然Squarespace给画廊容器加了内联样式的固定宽高(取所有图片的最大值),导致字幕无法紧贴不同尺寸的图片,我们可以用JavaScript动态修改容器的内联样式,让容器尺寸完全匹配当前显示的图片,从而让字幕位置统一。

具体实现步骤

  1. 监听幻灯片切换与图片加载
    每次切换幻灯片时,需要重新获取当前显示图片的实际尺寸。同时要确保图片加载完成后再计算,避免拿到未加载完成的错误尺寸。

  2. 动态调整容器尺寸
    获取当前图片的宽高后,直接覆盖容器的内联width和height样式,让容器完全贴合图片。

  3. 处理窗口缩放场景
    视口变化时图片尺寸会重新计算,所以要监听resize事件,同步更新容器尺寸。

代码示例

// 目标选择器(根据你的网站实际DOM结构调整)
const galleryContainerSelector = '.sqs-gallery-container';
const activeSlideImgSelector = '.sqs-active-slide img';

function adjustGalleryContainer() {
  const container = document.querySelector(galleryContainerSelector);
  const activeImg = document.querySelector(activeSlideImgSelector);
  
  if (!container || !activeImg) return;

  // 确保图片加载完成
  if (activeImg.complete) {
    // 获取图片实际渲染的宽高
    const imgWidth = activeImg.getBoundingClientRect().width;
    const imgHeight = activeImg.getBoundingClientRect().height;
    
    // 覆盖内联样式
    container.style.width = `${imgWidth}px`;
    container.style.height = `${imgHeight}px`;
  } else {
    activeImg.onload = () => adjustGalleryContainer();
  }
}

// 初始化执行
adjustGalleryContainer();

// 监听幻灯片切换(用MutationObserver监听活跃幻灯片的变化)
const gallery = document.querySelector(galleryContainerSelector);
if (gallery) {
  const observer = new MutationObserver((mutations) => {
    mutations.forEach(() => {
      adjustGalleryContainer();
    });
  });
  
  observer.observe(gallery, { attributes: true, childList: true, subtree: true });
}

// 监听窗口缩放
window.addEventListener('resize', adjustGalleryContainer);

注意事项

  • 请根据你网站的实际DOM结构调整选择器(可以通过Chrome开发者工具查看元素类名)。
  • 如果Squarespace的幻灯片有自带的切换事件(比如自定义事件),也可以直接监听该事件,比MutationObserver更高效。
  • 测试极端视口(极宽/极高)下的表现,确保所有场景下字幕间距一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 00:07:08