萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網頁製作 >> HTML 腳本教學

彈出式 Div 置中定位:相容 IE6~現代瀏覽器的完整 CSS/JS 實作

核心 CSS:固定定位 + 負邊距置中

.mydiv {
  position: fixed;           /* 現代瀏覽器:相對視窗定位 */
  _position: absolute;       /* IE6 hack:相對文件定位 */
  top: 50%; left: 50%;       /* 左上角對齊視窗中心 */
  width: 300px; height: 120px;
  margin-left: -150px;       /* 寬度一半負值 */
  margin-top: -60px;         /* 高度一半負值 */
  _margin-top: 0;            /* IE6 覆蓋 */
  z-index: 99;
  background: #ff6; border: 1px solid #f90;
  text-align: center; line-height: 40px;
}

/* IE6 專用:使用 expression 動態計算捲動位置 */
_mydiv {
  _top: expression(eval(document.compatMode && document.compatMode=='CSS1Compat') ?
    documentElement.scrollTop + (document.documentElement.clientHeight - this.offsetHeight)/2 :
    document.body.scrollTop + (document.body.clientHeight - this.clientHeight)/2);
}

半透明遮罩層

.bg {
  position: fixed; _position: absolute;
  top: 0; left: 0; width: 100%; height: 100%;
  background: #ccc; opacity: 0.5; filter: alpha(opacity=50);
  z-index: 1;
  /* IE6 同樣需 expression 修正捲動位置 */
}

JS 控制顯示/隱藏

function showDiv() {
  document.getElementById('popDiv').style.display = 'block';
  document.getElementById('bg').style.display = 'block';
}
function closeDiv() {
  document.getElementById('popDiv').style.display = 'none';
  document.getElementById('bg').style.display = 'none';
}

HTML 結構

<div id="popDiv" class="mydiv" style="display:none;">
  標題<br/>內容<br/>
  <a href="javascript:closeDiv()">關閉窗口</a>
</div>
<div id="bg" class="bg" style="display:none;"></div>

<input type="button" value="顯示層" onclick="showDiv()" />

進階樣式範例:帶標題列與關閉鈕的彈窗

<div id="mesWindow" class="mesWindow" style="top:180px; position:absolute; width:600px; margin-left:-300px; left:50%; z-index:9999;">
  <div class="mesWindowTop">
    <table width="100%"><tr>
      <td>窗口標題</td>
      <td style="width:1px;"><input type="button" value="關閉" onclick="closeWindow();"></td>
    </tr></table>
  </div>
  <div id="mesWindowContent" class="mesWindowContent">
    <div style="padding:20px 0; text-align:center;">消息正文</div>
  </div>
  <div class="mesWindowBottom"></div>
</div>

搭配 CSS:

.mesWindow { background:#fff; border:1px solid #666; }
.mesWindowTop { font:bold 12px; text-align:left; }
.mesWindowContent { font:12px; }

現代簡潔寫法(不支援 IE6)

.modal {
  position: fixed; top: 50%; left: 50%;
  transform: translate(-50%, -50%); /* 完美置中,無需知道寬高 */
  z-index: 1000;
}
.overlay {
  position: fixed; top: 0; left: 0; right: 0; bottom: 0;
  background: rgba(0,0,0,0.5); z-index: 999;
}

配合 flex 或 grid 更易處理內容置中。專案若無 IE6 包袱,強烈建議採用現代寫法。

copyright © 萬盛學電腦網 all rights reserved