React+Sass开发轮播图时hover触发后最后一张图片消失问题求解
问题原因
.listItem 触发hover时设置的position: absolute会让该元素脱离正常文档流,flex布局的.container宽度为max-content,会自动减去这个脱离元素原本占据的230px(225px宽度+5px右margin),容器整体宽度收缩后,原本排在最后的子项会被挤出可视区域,表现为消失。
解决方案
方案1:调整DOM结构,外层占位、内层悬浮(推荐)
不修改原有交互逻辑,仅给每个轮播项新增一层固定占位的父容器,保证hover时容器总宽度不会变化,结构修改如下:
// 原轮播项结构 <div className="listItem"> <img src="xxx" /> {/* 其他轮播项内容 */} </div> // 修改后结构 <div className="listItemWrapper"> <div className="listItem"> <img src="xxx" /> {/* 其他轮播项内容 */} </div> </div>
对应SCSS调整:
// 新增外层占位样式,固定占住原轮播项的位置 .listItemWrapper { width: 225px; height: 120px; margin-right: 5px; position: relative; flex-shrink: 0; // 禁止flex自动收缩,保证占位宽度固定 } // 调整原listItem样式 .listItem { // 移除原有width、height、margin-right配置 width: 100%; height: 100%; background-color: var(--main-color); cursor: pointer; color: white; img { width: 100%; height: 100%; object-fit: cover; } &:hover{ width: 325px; height: 300px; position: absolute; top: -150px; left: 0; // 对齐外层占位容器左边界,保证位置正确 z-index: 10; // 保证悬浮项层级高于其他轮播项 -webkit-box-shadow: 0px 0px 15px 0px rgba(255, 255, 255, 0.07); box-shadow: 0px 0px 15px 0px rgba(255, 255, 255, 0.07); border-radius: 5px; img { height: 140px; } } }
方案2:无DOM结构修改方案
如果不想调整DOM结构,可以用transform替代position: absolute实现悬浮放大效果,不会触发元素脱离文档流,也就不会导致容器宽度收缩:
.listItem { width: 225px; height: 120px; background-color: var(--main-color); margin-right: 5px; cursor: pointer; color: white; transition: all 0.2s ease; transform-origin: center top; // 缩放基点设为顶部中心,匹配原有悬浮展示效果 img { width: 100%; height: 100%; object-fit: cover; } &:hover{ // 移除position: absolute、top: -150px配置 transform: scale(1.4) translateY(-150px); z-index: 10; -webkit-box-shadow: 0px 0px 15px 0px rgba(255, 255, 255, 0.07); box-shadow: 0px 0px 15px 0px rgba(255, 255, 255, 0.07); border-radius: 5px; img { height: 140px; } } }
内容的提问来源于stack exchange,提问作者MajorLazer
相关产品推荐
相关产品推荐

