Vue点击空白关闭弹窗

<!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>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值