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'; + }} + /> +
+ ))} +
+ + {/* 内联样式 */} +
); };