需要強制使用者先處理某件事才能繼續操作時,遮罩是最有效的手段。原理很單純:鋪一層半透明黑色層蓋住整個視窗,再把提示框疊在上面。
<!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>
prepend 把遮罩 div 插入 body 開頭。這個範例用 alert 示意,但 alert 本身就會阻擋操作,實際專案通常需要:
$("#zhezhaoc").remove() 移除遮罩。position:fixed 搭配 left:50%; top:50%; transform:translate(-50%,-50%)。position:fixed; width:100%; height:100% 讓它自動跟著視窗。<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 細節。