`window.open()` **無法** 實現真正的模態對話框 (阻塞父頁面交互)。瀏覽器安全機制禁止 JS 控制新窗口模態行為。
.modal-overlay {
position: fixed; top: 0; left: 0; width: 100%; height: 100%;
background: rgba(0,0,0,0.6); z-index: 9998;
display: none; /* 默認隱藏 */
}
.modal-dialog {
position: fixed; top: 50%; left: 50%; transform: translate(-50%, -50%);
background: white; padding: 20px; border-radius: 8px; z-index: 9999;
min-width: 300px; max-width: 80%; max-height: 80vh; overflow: auto;
display: none;
}
function openModal(htmlContent) {
document.querySelector('.modal-overlay').style.display = 'block';
var dialog = document.querySelector('.modal-dialog');
dialog.innerHTML = htmlContent;
dialog.style.display = 'block';
// 防止背景滾動
document.body.style.overflow = 'hidden';
}
function closeModal() {
document.querySelector('.modal-overlay').style.display = 'none';
document.querySelector('.modal-dialog').style.display = 'none';
document.body.style.overflow = '';
}
// 觸發示例
document.getElementById('btnOpen').onclick = function() {
openModal('提示
這是模擬的模態對話框
');
};
class Modal {
constructor() {
this.overlay = this.createOverlay();
this.dialog = this.createDialog();
document.body.append(this.overlay, this.dialog);
this.overlay.onclick = () => this.close(); // 點遮罩關閉
}
createOverlay() { /* ... */ }
createDialog() { /* ... */ }
open(content) { /* ... */ }
close() { /* ... */ }
}
const modal = new Modal();
modal.open(''); // 甚至可嵌入 iframe 模擬 window.open
**放棄 `window.open` 實現模態**。採用 **單頁應用內遮罩層 + 彈出容器** 方案,或直接使用成熟 UI 庫 (Bootstrap Modal, Element UI Dialog, Ant Design Modal, SweetAlert2 等),功能完善、無障礙支持、移動端適配完美。