如何实现点击按钮弹出带暗化图片的弹窗区块
实现点击按钮弹出带暗化图片的区块
下面直接上可运行的代码方案,核心思路是用一个默认隐藏的模态弹窗,点击按钮时显示它,同时给图片加上暗化效果:
完整代码示例
<!DOCTYPE html> <html> <head> <style> /* 按钮样式 */ .show-btn { padding: 10px 20px; font-size: 16px; cursor: pointer; background: #2196F3; color: white; border: none; border-radius: 4px; } /* 模态框遮罩层 */ .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.7); display: none; /* 默认隐藏 */ justify-content: center; align-items: center; } /* 模态框内容区 */ .modal-content { position: relative; padding: 0; border-radius: 8px; overflow: hidden; } /* 暗化图片的两种方式选一种就行 */ /* 方式1:用CSS滤镜调亮度 */ .darkened-img { width: 600px; height: auto; filter: brightness(0.5); /* 数值越小越暗,0是全黑,1是原图 */ } /* 方式2:给图片加半透明遮罩层 */ /* .img-wrapper { position: relative; } .img-wrapper::after { content: ''; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); pointer-events: none; } */ /* 关闭按钮 */ .close-btn { position: absolute; top: 10px; right: 15px; font-size: 28px; font-weight: bold; color: white; cursor: pointer; } </style> </head> <body> <!-- 触发按钮 --> <button class="show-btn">点击弹出暗化图片</button> <!-- 模态弹窗 --> <div class="modal-overlay" id="modal"> <div class="modal-content"> <span class="close-btn">×</span> <!-- 方式1的图片写法 --> <img src="你的图片地址.jpg" class="darkened-img" alt="暗化图片"> <!-- 方式2的图片写法(需要用上上面注释的.img-wrapper样式) --> <!-- <div class="img-wrapper"> <img src="你的图片地址.jpg" width="600" height="auto" alt="暗化图片"> </div> --> </div> </div> <script> const btn = document.querySelector('.show-btn'); const modal = document.getElementById('modal'); const closeBtn = document.querySelector('.close-btn'); // 点击按钮显示弹窗 btn.onclick = function() { modal.style.display = 'flex'; } // 点击关闭按钮隐藏弹窗 closeBtn.onclick = function() { modal.style.display = 'none'; } // 点击遮罩层也关闭弹窗 window.onclick = function(event) { if (event.target == modal) { modal.style.display = 'none'; } } </script> </body> </html>
关键说明说明
- 模态弹窗的遮罩层用
position: fixed占满全屏,默认隐藏,点击按钮后通过display: flex居中显示内容。 - 图片暗化有两种常用方法:
- CSS滤镜:直接给图片加
filter: brightness(0.5),数值可根据需求调整,0全黑,1原图亮度。 - 遮罩层叠加:给图片套一个父容器,用伪元素加半透明黑色层,好处是不修改图片本身,还能在遮罩上加其他内容。
- CSS滤镜:直接给图片加
- 弹窗关闭逻辑:支持点击关闭按钮和点击遮罩层两种方式,符合用户习惯。
内容的提问来源于stack exchange,提问作者Serhii
相关产品推荐
相关产品推荐

