<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Vue点击空白关闭弹窗</title>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<style>
body {
font-family: Arial, sans-serif;
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
margin: 0;
background-color: #f5f5f5;
}
.modal-overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
background-color: rgba(0, 0, 0, 0.5);
display: flex;
justify-content: center;
align-items: center;
z-index: 1000;
}
.modal-content {
background-color: white;
padding: 20px;
border-radius: 8px;
box-shadow: 0 2px 10px rgba(0, 0, 0, 0.2);
max-width: 500px;
width: 80%;
}
button {
padding: 10px 20px;
background-color: #42b983;
color: white;
border: none;
border-radius: 4px;
cursor: pointer;
font-size: 16px;
}
button:hover {
background-color: #369f6b;
}
h2 {
margin-top: 0;
color: #333;
}
p {
color: #666;
}
.link {
margin-top: 20px;
color: #42b983;
text-decoration: none;
}
</style>
</head>
<body>
<div id="app">
<button @click="showModal = true">打开弹窗</button>
<div v-if="showModal" class="modal-overlay" @click.self="closeModal">
<div class="modal-content">
<h2>这是一个弹窗</h2>
<p>点击弹窗外部区域可以关闭此弹窗。</p>
<p>弹窗内容可以放在这里...</p>
<button @click="closeModal" style="margin-top: 15px;">关闭弹窗</button>
</div>
</div>
</div>
<script>
new Vue({
el: '#app',
data: {
showModal: false
},
methods: {
closeModal() {
this.showModal = false;
}
},
mounted() {
// 也可以添加ESC键关闭功能
document.addEventListener('keydown', (e) => {
if (e.key === 'Escape' && this.showModal) {
this.closeModal();
}
});
}
});
</script>
</body>
</html>