HTML/CSS实现图片hover/点击时居中显示原尺寸,操作后恢复缩略大小
完整实现代码
<html> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <style> @import url('https://fonts.googleapis.com/css2?family=Open+Sans:wght@300&display=swap'); body { font-family: 'Open Sans', sans-serif; min-height: 100vh; position: relative; margin: 0; padding: 20px; box-sizing: border-box; } /* 缩略图基础样式 */ .im { width: 300px; float: left; margin: 10px; cursor: pointer; transition: all 0.2s ease; position: relative; z-index: 1; } /* 放大状态样式,hover和点击触发都可用 */ .im:hover, .im.expanded { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); z-index: 9999; width: auto; height: auto; max-width: 90vw; max-height: 90vh; box-shadow: 0 0 24px rgba(0,0,0,0.8); float: none; margin: 0; } /* 半透明遮罩层,放大时显示 */ body.has-active-img::before { content: ''; position: fixed; top: 0; left: 0; width: 100vw; height: 100vh; background: rgba(0,0,0,0.7); z-index: 9998; } </style> </head> <body> <p>Test hello</p> <img class="im" src="Freedom.jpg" alt="示例图片" /> <img class="im" src="example2.jpg" alt="示例图片2" /> <script> const imgs = document.querySelectorAll('.im'); const body = document.body; imgs.forEach(img => { img.addEventListener('click', (e) => { e.stopPropagation(); // 切换当前图片的放大状态 img.classList.toggle('expanded'); // 切换body的遮罩显示状态 const hasActive = document.querySelector('.im.expanded'); body.classList.toggle('has-active-img', !!hasActive); }) }) // 点击遮罩区域关闭放大的图片 body.addEventListener('click', () => { const activeImg = document.querySelector('.im.expanded'); if(activeImg) { activeImg.classList.remove('expanded'); body.classList.remove('has-active-img'); } }) </script> </body> </html>
功能说明
- 布局兼容:保留原需求的缩略图统一300px宽度、左浮动整齐排布的效果
- 桌面端交互:hover悬浮在图片上自动居中放大,移出hover自动恢复缩略尺寸
- 移动端交互:点击图片放大,再次点击图片或遮罩区域即可恢复缩略尺寸
- 尺寸限制:放大后的图片最大宽高不超过屏幕的90%,自动适配图片原始比例,不会拉伸变形
内容的提问来源于stack exchange,提问作者Alasdair
相关产品推荐
相关产品推荐

