From bf0958db935ec58a7661a9572cb155c4831974d1 Mon Sep 17 00:00:00 2001 From: jingrow Date: Sun, 24 Aug 2025 19:42:16 +0800 Subject: [PATCH] =?UTF-8?q?=E4=BC=98=E5=8C=96=E4=BA=A7=E5=93=81=E8=AF=A6?= =?UTF-8?q?=E6=83=85=E9=A1=B5=E7=BC=A9=E7=95=A5=E5=9B=BE=E6=95=88=E6=9E=9C?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- components/products/ProductImageGallery.jsx | 171 ++++++++++++++++---- 1 file changed, 141 insertions(+), 30 deletions(-) diff --git a/components/products/ProductImageGallery.jsx b/components/products/ProductImageGallery.jsx index 7464d8d..3a77523 100644 --- a/components/products/ProductImageGallery.jsx +++ b/components/products/ProductImageGallery.jsx @@ -1,9 +1,10 @@ 'use client'; -import { useState, useEffect } from 'react'; +import { useState, useEffect, useRef } from 'react'; const ProductImageGallery = ({ data }) => { const [currentImageIndex, setCurrentImageIndex] = useState(0); + const thumbnailContainerRef = useRef(null); // 如果没有attachments,不显示组件 if (!data?.attachments || data.attachments.length === 0) { @@ -43,64 +44,174 @@ const ProductImageGallery = ({ data }) => { setCurrentImageIndex(index); }; + // 智能滚动到缩略图 - 业内最佳实践 + const scrollToThumbnail = (index) => { + if (!thumbnailContainerRef.current) return; + + const container = thumbnailContainerRef.current; + const containerWidth = container.clientWidth; + const thumbnailWidth = 64; // 64px 缩略图宽度 + const gap = 16; // 16px 间距 + const totalThumbnailWidth = thumbnailWidth + gap; + + // 计算一次能显示多少个缩略图(类似Swiper的slidesPerView) + const visibleCount = Math.floor(containerWidth / totalThumbnailWidth); + + // 计算目标滚动位置 + let scrollLeft; + + if (index < visibleCount / 2) { + // 如果是前几个,滚动到开头 + scrollLeft = 0; + } else if (index >= data.attachments.length - visibleCount / 2) { + // 如果是后几个,滚动到末尾 + scrollLeft = container.scrollWidth - containerWidth; + } else { + // 居中显示 + scrollLeft = (index - Math.floor(visibleCount / 2)) * totalThumbnailWidth; + } + + // 确保滚动位置在有效范围内 + scrollLeft = Math.max(0, Math.min(scrollLeft, container.scrollWidth - containerWidth)); + + container.scrollTo({ + left: scrollLeft, + behavior: 'smooth' + }); + }; + return ( -
+
{/* 主图显示区域 */} -
+
{data?.title - {/* 导航箭头 */} + + {/* 导航箭头 - 简约大气设计 */} {data.attachments.length > 1 && ( <> )}
- {/* 缩略图列表 - 直接显示attachments */} -
- {data.attachments.map((attachment, index) => ( -
changeMainImageByIndex(index)} - > - {`${data?.title { - console.error('Image load error:', attachment.file_url); - e.target.style.display = 'none'; + {/* 缩略图列表 - 业内最佳实践,确保完整显示 */} +
+
+ {data.attachments.map((attachment, index) => ( +
{ + changeMainImageByIndex(index); + scrollToThumbnail(index); }} - /> -
- ))} + > + {`${data?.title { + console.error('Image load error:', attachment.file_url); + e.target.style.display = 'none'; + }} + /> +
+ ))} +
+ + {/* 内联样式 */} +
); };