如何通过JavaScript或jQuery点击指定区域关闭弹窗?
实现点击遮罩或内容块关闭弹窗的方案
你只需要给弹窗容器添加点击事件,通过判断点击目标来触发关闭逻辑,以下是修改后的完整代码:
完整代码
HTML
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <button class="js-btn">click</button> <div class="popup"> <div class="wrap">content</div> </div>
CSS
.popup { position: fixed; width: 100%; height: 100vh; top: 0px; right: 0px; left: 0px; justify-content: center; align-items: center; background-color: rgba(0, 0, 0, 0.2); z-index: 999; display: none; } .popup .wrap { display: inline-block; width: 300px; height: 300px; background-color: yellow; }
JavaScript
// 打开弹窗 $('.js-btn').on('click',function(e){ $('.popup').css('display','flex'); }) // 关闭弹窗 $('.popup').on('click', function(e) { // 判断点击的是遮罩层(popup本身)还是黄色内容块(wrap) if ($(e.target).hasClass('popup') || $(e.target).hasClass('wrap')) { $(this).css('display', 'none'); } });
代码说明
- 给
.popup绑定点击事件,当用户点击弹窗区域时触发 e.target表示实际被点击的DOM元素,通过hasClass()方法判断它是否是遮罩层或内容块- 如果符合条件,就将弹窗的
display设为none,实现关闭效果
内容的提问来源于stack exchange,提问作者AWEI
相关产品推荐
相关产品推荐

