Unity中如何实现点击背景区域关闭窗口且点击窗口本身不关闭?
实现点击灰色背景关闭弹窗、点击弹窗本身不关闭的方案
核心思路是利用事件冒泡机制:点击弹窗内部时阻止事件向上传递,避免触发背景层的关闭逻辑;点击背景层时直接执行关闭操作。
原生HTML+CSS+JS实现
1. HTML结构
<!-- 灰色背景遮罩层 --> <div class="modal-overlay" id="modalOverlay"></div> <!-- 弹窗容器 --> <div class="modal-window" id="modalWindow"> <div class="modal-content"> <h3>示例弹窗</h3> <p>点击弹窗内部不会关闭,点击灰色背景才会关闭</p> </div> </div> <!-- 打开弹窗的按钮 --> <button onclick="openModal()">打开弹窗</button>
2. CSS样式
/* 遮罩层样式:全屏灰色半透明,默认隐藏 */ .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background-color: rgba(0, 0, 0, 0.5); display: none; z-index: 1000; } /* 弹窗样式:居中显示,默认隐藏 */ .modal-window { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background-color: #fff; padding: 24px; border-radius: 8px; display: none; z-index: 1001; /* 确保弹窗在遮罩层上方 */ } /* 激活状态:显示遮罩和弹窗 */ .modal-overlay.active, .modal-window.active { display: block; }
3. JavaScript逻辑
const overlay = document.getElementById('modalOverlay'); const modal = document.getElementById('modalWindow'); // 打开弹窗函数 function openModal() { overlay.classList.add('active'); modal.classList.add('active'); } // 关闭弹窗函数 function closeModal() { overlay.classList.remove('active'); modal.classList.remove('active'); } // 点击遮罩层关闭弹窗 overlay.addEventListener('click', closeModal); // 点击弹窗内部时,阻止事件冒泡,避免触发遮罩层的关闭逻辑 modal.addEventListener('click', (e) => { e.stopPropagation(); });
Vue框架实现(更简洁)
利用Vue的@click.stop修饰符直接阻止事件冒泡:
<template> <div> <button @click="showModal = true">打开弹窗</button> <!-- 灰色背景遮罩 --> <div class="modal-overlay" v-if="showModal" @click="showModal = false" ></div> <!-- 弹窗容器 --> <div class="modal-window" v-if="showModal" @click.stop > <div class="modal-content"> <h3>Vue弹窗</h3> <p>点击弹窗内部不会关闭,点击灰色背景关闭</p> <button @click="showModal = false">手动关闭</button> </div> </div> </div> </template> <script setup> import { ref } from 'vue'; const showModal = ref(false); </script> <style scoped> .modal-overlay { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.5); } .modal-window { position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%); background: #fff; padding: 24px; border-radius: 8px; } </style>
内容的提问来源于stack exchange,提问作者Rez_Ait
相关产品推荐
相关产品推荐

