萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript 點擊按鈕彈出居中透明浮動層(模態對話框)

效果特色

  • 點擊按鈕 → 頁面變灰(半透明遮罩) → 置中彈出透明邊框對話框
  • 對話框支援標題、任意 HTML 內容、關閉鈕
  • 遮罩 opacity:0.7,對話框 top:25% 垂直置中偏上
  • 全純 JS/CSS,無圖片依賴(關閉鈕為 x.gif 可替換為 CSS 繪製)

核心類別:NeatDialog

function NeatDialog(html, title, showCloseBtn) {
  if (!document.createElement) return;
  // 建立遮罩層
  var bg = document.createElement('div');
  bg.className = 'neat-dialog-bg'; // z-index:-1, 絕對定位全螢幕, opacity:0.7
  // 建立容器層
  var container = document.createElement('div');
  container.className = 'neat-dialog-cont'; // z-index:98, 全螢幕承載
  // 建立對話框
  var dlg = document.createElement('div');
  dlg.className = 'neat-dialog'; // z-index:99, 寬30%, 相對定位 top:25%
  if (title) {
    var closeBtn = showCloseBtn ? '<img src="x.gif" class="nd-cancel">' : '';
    dlg.innerHTML = '<div class="neat-dialog-title">' + title + closeBtn + '</div>' + html;
  } else dlg.innerHTML = html;
  container.appendChild(bg); container.appendChild(dlg);
  document.body.appendChild(container);
  this.elt = container;
  window.neatDialog = this; // 全域單例引用
  if (showCloseBtn) document.getElementById('nd-cancel').onclick = this.close.bind(this);
}
NeatDialog.prototype.close = function() {
  if (this.elt) { this.elt.style.display = 'none'; this.elt.parentNode.removeChild(this.elt); }
  window.neatDialog = null;
};

CSS 關鍵樣式

.neat-dialog-cont { position:absolute; left:0; top:0; width:100%; height:100%; z-index:98; }
.neat-dialog-bg { position:absolute; left:0; top:0; width:100%; height:100%; background:#eee; opacity:0.7; filter:alpha(opacity=70); z-index:-1; }
.neat-dialog { position:relative; top:25%; width:30%; margin:auto; border:1px solid #555; background:#fff; z-index:99; }
.neat-dialog-title { padding:0.1em 0.3em; border-bottom:1px solid #444; font-size:0.8em; line-height:1.2; position:relative; }
.nd-cancel { position:absolute; right:0.2em; top:0.2em; cursor:pointer; }

呼叫範例

function openDialog() {
  var html = '<p>這是 JS 控制彈出的層視窗</p><p><button onclick="window.neatDialog.close()">關閉</button></p>';
  new NeatDialog(html, '你知道嗎?', false);
}
<button onclick="openDialog()">點此演示</button>

改良建議

  • 移除 window.neatDialog 全域單例,改回傳實例讓呼叫端管理。
  • 加入 Esc 鍵關閉、點擊遮罩關閉、focus trap 無障礙支援。
  • 使用 position:fixed + transform:translate(-50%,-50%) 真正置中,不受捲動影響。
copyright © 萬盛學電腦網 all rights reserved