求助:实现自适应高度可横向滚动背景图与固定点击热点
网页复刻需求与实现方案
需求说明
- 背景图高度始终匹配屏幕高度,同时保持原始宽高比;
- 当图片宽度超过设备屏幕时,支持横向滚动查看完整图片;
- 可点击热点在任何屏幕尺寸下,都固定在背景图的指定位置。
问题分析
当前实现中使用了object-cover属性,会裁剪图片以填充容器,导致热点定位偏离预期;同时容器宽度设置为w-full,无法让图片按比例扩展宽度并触发横向滚动。
解决方案
1. 调整图片布局(适配屏幕高度+横向滚动)
- 最外层容器添加
overflow-x-auto,当图片宽度超出屏幕时自动显示横向滚动条; - 图片的直接父容器设置为
inline-block h-full relative,让容器宽度完全跟随图片的实际渲染宽度,为热点提供正确的定位参考; - 移除Next.js Image组件的
object-cover和w-full,改用h-full w-auto,确保图片高度填满屏幕,宽度按原始宽高比自动计算,避免裁剪。
2. 修正热点定位逻辑
- 确保热点的
left/top属性为基于图片尺寸的百分比值(例如left: "25%"),这样无论图片如何缩放,热点都会保持在图片的对应位置; - 保留
transform: translate(-50%, -50%),让热点的中心点对齐目标位置。
修改后的代码
export const Bedroom = ({ blurDataURL, hotspots }: BedroomProps) => { return ( <section id="bedroom" className="h-screen overflow-x-auto"> {/* 容器宽度随图片自适应,为热点提供正确定位基准 */} <div className="relative inline-block h-full"> <Image src={src} alt={title} placeholder="blur" blurDataURL={blurDataURL} width={4000} height={2500} className={cn("h-full w-auto")} /> {hotspots.map((hotspot, index) => ( <div key={index} className="absolute" style={{ left: hotspot?.position?.left, top: hotspot?.position?.top, transform: "translate(-50%, -50%)", }} > <Popover> <PopoverTrigger asChild> <div className="relative size-10 flex items-center justify-center cursor-pointer"> <div className="bg-white rounded-full p-3 animate-slow-ping opacity-65" /> <div className="bg-white rounded-full p-1 animate-none shadow absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 z-2" /> </div> </PopoverTrigger> <PopoverContent className={cn( GeistSans.className, "rounded-full capitalize text-sm lg:text-base font-medium tracking-tight px-4 py-1.5" )} > <a href={hotspot?.href}> <div>{hotspot?.name}</div> </a> </PopoverContent> </Popover> </div> ))} </div> </section> ); };
内容的提问来源于stack exchange,提问作者Joshua Edo
相关产品推荐
相关产品推荐

