CSS Grid布局商品图片悬停切换效果 求适合新手的更简易实现方案
简化实现方案
你的原有实现逻辑是可行的,以下是更精简、易维护的写法,完全满足悬停切换图片、服务端动态渲染的需求:
优化后HTML代码
<div class="product__div"> <h2>New Products</h2> </div> <div class="product__grid"> <% products.forEach(product => { %> <a href="products/<%=product.id%>"> <figure> <div class="product__img_wrap"> <img src="<%=product.img%>h.webp" alt="Minalva" class="img__hover"> <img src="<%=product.img%>.webp" alt="Minalva" class="img__default"> </div> <p class="title"><%=product.category%></p> <p class="name"><%=product.title%></p> <p class="price"><%=product.price%> TL</p> </figure> </a> <% }) %> </div>
优化点:删掉了冗余的child1、child2嵌套div,减少DOM节点,结构更清晰;修正了forEach的参数命名(原参数和数组同名容易混淆)
优化后SASS代码
#products .product__div align-self: center margin-bottom: 40px h2 @include main-fonts($custom-color-5) .product__grid // 修正原有笔误:repeater改为repeat grid-template-columns: repeat(4, 1fr) --repeat: auto-fit column-gap: 25px row-gap: 40px display: grid .product__img_wrap display: grid grid-template-columns: 1fr // 两张图片共用相同的网格位置,实现重叠 img grid-area: 1 / 1 / 2 / 2 width: 100% height: 100% border-radius: 10px transition: opacity 500ms ease .img__default opacity: 1 .img__hover opacity: 0 .title margin-top: 25px text-transform: uppercase .name padding-top: 5px .price margin: 5px 0 25px 0 text-transform: uppercase a:hover .img__default opacity: 0 .img__hover opacity: 1
优化点:合并两张图片的重复样式,减少冗余代码;用grid-area简写网格位置属性,写法更简洁;修正了原有repeater的语法笔误
方案说明
该方案和你原有实现的交互效果完全一致,两个图片的src依然支持服务端直接注入变量渲染,代码量更少、结构更直观,新手更容易修改维护。
内容的提问来源于stack exchange,提问作者Kene
相关产品推荐
相关产品推荐

