[js] Create an alert funtion by javascript

2025-1-10 写技术

document.addEventListener('DOMContentLoaded', function() {


(function() {
    // 创建模态对话框的 HTML 结构
    var modalHTML = `
        <div id="myModal" class="modal">
            <div class="modal-content">
                <p id="modal-message"></p>
                <button id="confirm-button">确认</button>
            </div>
        </div>
    `;

    // 创建样式表
    var styleHTML = `
        <style>
            .modal {
                display: none; /* Hidden by default */
                position: fixed; /* Stay in place */
                z-index: 1; /* Sit on top */
                left: 0;
                top: 0;
                width: 100%; /* Full width */
                height: 100%; /* Full height */
                overflow: auto; /* Enable scroll if needed */
                background-color: rgb(0,0,0); /* Fallback color */
                background-color: rgba(0,0,0,0.4); /* Black w/ opacity */
            }

            .modal-content {
                background-color: #fefefe;
                margin: 15% auto; /* 15% from the top and centered */
                padding: 20px;
                border: 1px solid #888;
                width: 80%; /* Could be more or less, depending on screen size */
            }

        </style>
    `;

    // 将 HTML 和 CSS 插入到页面中
    document.head.insertAdjacentHTML('beforeend', styleHTML);
    document.body.insertAdjacentHTML('beforeend', modalHTML);

    // 获取模态对话框元素
    var modal = document.getElementById('myModal');
    var modalMessage = document.getElementById('modal-message');
    var confirmButton = document.getElementById('confirm-button');

    // 保存原始的 alert 函数
    var originalAlert = window.alert;

    // 重写 alert 函数
    window.alert = function(message) {
        // 设置消息
        modalMessage.textContent = message;

        // 显示模态对话框
        modal.style.display = 'block';


        // 当用户点击模态对话框外部区域时,隐藏模态对话框
        window.onclick = function(event) {
            if (event.target === modal) {
                modal.style.display = 'none';
            }
        };

        // 当用户点击确认按钮时,隐藏模态对话框
        confirmButton.onclick = function() {
            modal.style.display = 'none';
        };
    };

    // 提供恢复原始 alert 函数的方法
    window.restoreAlert = function() {
        window.alert = originalAlert;
    };
})();

});

标签: JS

发表评论:

Powered by anycle 湘ICP备15001973号-1