DIV CSS 佈局教程網

用 jQuery 做一個簡易的遮罩鎖屏提示框
編輯:JQuery特效代碼     

需要強制使用者先處理某件事才能繼續操作時,遮罩是最有效的手段。原理很單純:鋪一層半透明黑色層蓋住整個視窗,再把提示框疊在上面。

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>無標題文檔</title>
<script language="JavaScript" type="text/javascript" src="/js/jquery-1.8.3.min.js"></script>
<script language="JavaScript" type="text/javascript">
$(document).ready(function(){
  $('a').click(function(){
    var wwd = $(document).width();
    var wgd = $(document).height();
    $('body').prepend('<div id="zhezhaoc"></div>');
    $('#zhezhaoc').css({
      'width' : ''+wwd+'px',
      'height' : ''+wgd+'px',
      'background-color' : '#000000',
      'z-index' : '1100',
      'opacity' : '0.5',
      'position' : 'absolute',
      'top' : '0px',
      'left' : '0px'
    });
    alert('提示框任意');
  });
});
</script>
</head>

<body>
<a href="#">測試按鈕</a>

</body>
</html>

運作步驟

  1. 取得文件的寬高,作為遮罩的尺寸。
  2. 用 prepend 把遮罩 div 插入 body 開頭。
  3. 設定樣式:絕對定位覆蓋左上角、半透明、z-index 拉高到最上層。
  4. 後續再顯示提示內容。

要改成實用版本,還需要補上

這個範例用 alert 示意,但 alert 本身就會阻擋操作,實際專案通常需要:

  • 關閉機制:加上確認按鈕,點擊後 $("#zhezhaoc").remove() 移除遮罩。
  • 置中定位:提示框若要在畫面正中央,可用 position:fixed 搭配 left:50%; top:50%; transform:translate(-50%,-50%)。
  • 視窗縮放:目前只在點擊當下計算尺寸,視窗改變大小後遮罩就覆蓋不全,建議改用 position:fixed; width:100%; height:100% 讓它自動跟著視窗。
  • ESC 關閉與焦點管理:完整的 modal 應支援鍵盤操作,並把焦點鎖在對話框內。

改良版

<style>
#mask{
  position: fixed; top:0; left:0;
  width:100%; height:100%;
  background:#000; opacity:.5; z-index:1100;
}
#dialog{
  position: fixed; top:50%; left:50%;
  transform: translate(-50%,-50%);
  background:#fff; padding:20px 30px; z-index:1101;
  border-radius:4px; text-align:center;
}
</style>

<a href="#" id="openDialog">開啟提示</a>

<script>
$("#openDialog").click(function(){
  $("body").append('<div id="mask"></div><div id="dialog">確定要繼續嗎?<br><button id="closeDialog">確定</button></div>');
  $("#closeDialog").click(function(){
    $("#mask, #dialog").remove();
  });
});
</script>

若專案已導入 UI 框架,直接用既有的 Modal 元件會更省事,也能少處理無障礙與焦點 these 細節。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved