刷新聞時常看到那種效果:點擊回複,整頁暗下來,中間浮出一層評論框,點擊周圍區域即可關閉。研究之後自己模擬了一版,在 IE8、Chrome、Firefox 下都能正常跑。核心思路是:主頁面與遮罩是兩個獨立頁面,遮罩透過 iframe 由 JavaScript 動態掛載進來。
<!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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<title>append-iframe</title>
<style type="text/css">
html,body{height:100%;padding:0px;margin:0px;}
</style>
</head>
<body>
<div><input type="button" value="show" id="show-id"/></div>
<div><input type="button" value="test" id="test-id"/></div>
<script type="text/javascript">
$("#show-id").on("click",function(){
$(top.document.body).append('<iframe src="subiframe.html" id="np-pop-iframe" allowtransparency="true" frameborder="0" scrolling="no" style="width: 100%; z-index: 9999; position: fixed; top: 0px; left: 0px; border: none; overflow: hidden; height: 100%;" data-nick="" data-pic="" data-id="" parentid=""></iframe>');
});
$("#test-id").on("click",function(){
alert("test");
});
</script>
</body>
</html>
<!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" xml:lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<title>Document</title>
<style type="text/css">
html,body{height:100%;padding:0px;margin:0px;}
.np-popframe-bg-opacity{
filter: alpha(opacity=50);
-moz-opacity: 0.5;
opacity: 0.5;
}
.wrapper{
position: absolute;
border:1px solid red;
width:800px;
height: 800px;
background: #fff;
top:1000px;
left:500px;
}
</style>
</head>
<body class="iframe-body">
<div class="np-popframe-bg-opacity" style="height: 100%; width:100%; background-color:#000;"></div>
<div class="np-popframe-bg" id="np-popframe-bg-id" style="height: 100%; width:100%; position:absolute; top:0px; left:0px;"></div>
<div class="wrapper" id="wrapper-id"></div>
</body>
<script type="text/javascript">
(function(){
$("#wrapper-id").animate({top:"100px"},"slow");
$("#np-popframe-bg-id").on("click",function(){
$("#np-pop-iframe",window.parent.document).remove();
});
})(jQuery);
</script>
</html>
1. 透明遮罩層。np-popframe-bg-opacity 這一層負責鋪出半透明的黑色背景,三行 opacity 寫法是為了兼容舊 IE。id 為 np-popframe-bg-id 的透明層則鋪在最上方承接點擊事件——滑鼠點到框外區域時,就移除整個 iframe,實現「點擊周圍關閉」。
2. 高度百分比要配 html,body 一起寫。如果希望內部 div 撐滿 100% 高度,必須先給 html 和 body 都設 height:100%,否則百分比高度無效,這一點很容易漏。
3. 定位方式的選擇。wrapper 用了 absolute 配合 animate 做出從下滑入的動畫。若改成 fixed 定位,居中會省事很多,但舊 IE 對 fixed 的支援不佳,當年只能退而求其次。
記錄於此,聊備不忘。今天若重做這個需求,直接上 <dialog> 元素或一個 fixed 定位的遮罩層會乾淨得多,不必再繞 iframe 這一圈。