遮罩層的做法很直覺:動態產生一個鋪滿全頁的半透明 div 插到 body,需要時 show、關閉時 hide。
<script type="text/javascript">
$("<div id='div_mask'><img id='close_mask' src='nav-close.png' /></div>").css({
position: "absolute",
top: 0,
left: 0,
backgroundColor: "#004400",
opacity: 0.5,
zIndex: 300
})
.height($(document).height())
.width($(document).width())
.hide()
.appendTo("body");
// 需要遮罩時
function showMask() {
$("#div_mask").show();
}
$("#close_mask").click(function () {
$("#div_mask").hide();
});
</script>
$(selector).show(speed, callback); $(selector).hide(speed, callback);
speed 可選,可以是毫秒數或 "slow"、"normal"、"fast"。設定速度後,元素在顯示或隱藏過程中會平滑改變高度、寬度、内外距與透明度;未設速度時則是瞬間切換。callback 只在設定了 speed 時才會被執行。
這兩個方法只對「透過 jQuery 隱藏」或「CSS 宣告 display:none」的元素有效,對 visibility:hidden 無作用。
用 position:fixed 取代 absolute,滾動時遮罩才不會跑掉;另外 CSS 屬性名稱要正確寫成 camelCase 或含大寫(backgroundColor、zIndex),原範例全小寫的寫法在 jQuery 的 .css() 中多數仍能運作,但不建議養成習慣。最後,遮罩顯示時鎖住背景捲動,並讓關閉鈕可用鍵盤 focus 到,對無障礙有實質幫助。