纯CSS实现点击放大、再次点击缩小的简易图片相册咨询
纯CSS实现点击切换图片放大/缩小方案
实现结论
可以纯CSS实现,无需引入JavaScript,仅需要对你原有代码做少量修改即可满足要求。
代码修改说明
- 修正原有CSS的非法属性:原有
justify-content: equally-spaced为无效值,替换为space-evenly实现均匀间距布局 - 新增可聚焦属性:给每张图片添加
tabindex="0"让图片可以响应点击获得焦点,用:focus伪类替代原有的:active伪类实现持久化放大状态 - 新增遮罩样式:放大时自动显示半透明背景,提升查看体验
完整可运行代码
.photo-galery-with-zoom { display: flex; width: 100%; flex-wrap: wrap; justify-content: space-evenly; position: relative; } /* 放大时的半透明遮罩 */ .photo-galery-with-zoom:focus-within::before { content: ""; position: fixed; inset: 0; background: rgba(0,0,0,0.8); z-index: 99998; } .photo-galery-with-zoom img { max-height: 19vh; margin: 5px; border-radius: 5px; border: 1px solid white; transition: filter .2s; cursor: pointer; outline: none; /* 移除默认的聚焦边框 */ } .photo-galery-with-zoom img:hover { filter: drop-shadow(0 0 4px black); } /* 聚焦时的放大样式 */ .photo-galery-with-zoom img:focus { position: fixed; left: 50%; top: 50%; transform: translate(-50%, -50%); max-width: 88vw; max-height: 88vh; z-index: 99999; transition: 0s; filter: none; }
<div class="photo-galery-with-zoom"> <img tabindex="0" src="https://hips.hearstapps.com/hmg-prod.s3.amazonaws.com/images/lionel-animals-to-follow-on-instagram-1568319926.jpg?crop=0.922xw:0.738xh;0.0555xw,0.142xh&resize=640:*"> <img tabindex="0" src="https://www.boredpanda.com/blog/wp-content/uuuploads/cute-baby-animals/cute-baby-animals-2.jpg"> <img tabindex="0" src="https://i.pinimg.com/736x/a7/c6/55/a7c65551c76a4870e9c9082d05750658.jpg"> </div>
效果说明
- 第一次点击任意图片,图片自动居中放大并显示半透明背景
- 再次点击图片、点击背景区域或者按ESC键,图片自动缩小回到缩略图状态
- 完全保留原有hover阴影效果,HTML结构依然仅用单个div包裹所有图片,仅给img新增了一个
tabindex属性,改动极小
内容的提问来源于stack exchange,提问作者user171780
相关产品推荐
相关产品推荐

