仅使用HTML和CSS能否在同一页面实现两个模态窗口?
结论
这个需求完全可以实现,不需要借助任何JavaScript代码,核心依赖CSS原生的:target伪类实现状态切换。
实现原理
:target是CSS的原生伪类,当页面URL的哈希值(也就是#后面的内容)和某个元素的id属性完全匹配时,:target伪类就会生效于该元素。我们可以通过这个特性,控制弹窗的显隐状态:
- 点击打开弹窗的链接时,URL哈希变更为对应弹窗的id,触发弹窗的
:target样式,弹窗显示 - 点击关闭按钮时,URL哈希重置,
:target失效,弹窗隐藏
完整实现代码
HTML部分
<!-- 弹窗触发链接 --> <a href="#modal1" class="open-modal-btn">打开第一个弹窗</a> <a href="#modal2" class="open-modal-btn">打开第二个弹窗</a> <!-- 第一个弹窗 --> <div class="modal" id="modal1"> <div class="modal-content"> <h3>第一个弹窗</h3> <p>这是第一个弹窗的专属内容</p> <a href="#" class="close-modal-btn">关闭弹窗</a> </div> </div> <!-- 第二个弹窗 --> <div class="modal" id="modal2"> <div class="modal-content"> <h3>第二个弹窗</h3> <p>这是第二个弹窗的专属内容</p> <a href="#" class="close-modal-btn">关闭弹窗</a> </div> </div>
CSS部分
/* 基础样式 */ .open-modal-btn { display: inline-block; margin: 20px; padding: 8px 16px; background: #2563eb; color: #fff; text-decoration: none; border-radius: 4px; } /* 弹窗默认隐藏 */ .modal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100vh; background: rgba(0, 0, 0, 0.6); z-index: 999; } /* 对应弹窗被触发时显示 */ .modal:target { display: flex; align-items: center; justify-content: center; } /* 弹窗内容样式 */ .modal-content { background: #fff; padding: 30px; border-radius: 8px; width: 90%; max-width: 500px; } /* 关闭按钮样式 */ .close-modal-btn { display: inline-block; margin-top: 20px; padding: 6px 12px; background: #ef4444; color: #fff; text-decoration: none; border-radius: 4px; }
额外说明
- 同一时间只会展示一个弹窗,因为URL的哈希值同一时间唯一,符合常规弹窗交互逻辑
- 浏览器前进后退按钮会自动匹配哈希变化,也可以控制弹窗开关
- 如果不希望点击关闭按钮后页面跳转到顶部,可以给页面根元素设置id为
page-top,之后将关闭按钮的href属性改为#page-top即可
内容的提问来源于stack exchange,提问作者ATR
相关产品推荐
相关产品推荐

