点击弹出层

此实例可说是十分常见,主要功能有:点击弹出层后背景变灰;点击背景任何一处关闭层;拉动滚动条时层的位置不变。

感觉代码不够精简。

 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 2 <html xmlns="http://www.w3.org/1999/xhtml">
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
 5 <title>弹出层</title>
 6 <style type="text/css">
 7 * {margin:0; padding:0;}
 8 #popup {position:absolute; display:none; width:500px; border:#ccc solid 5px; height:300px; z-index:10; background:#fff;}
 9 #wrap {position:absolute; top:0; left:0; width:100%; background:#eee; z-index:9; opacity:0.5; filter:alpha(opacity=50); cursor:pointer;}
10 </style>
11 </head>
12 <body>
13     <input type="button" value="submit" id="btn" />
14     <div id="popup"><a href="javascript:;" id="closeDiv">关闭</a></div>
15     <div style="height:2000px;" id="abc"></div>
16     <script type="text/javascript">
17     var obj_btn = document.getElementById("btn");
18     var obj_div = document.getElementById("popup");
19     var obj_link = document.getElementById("closeDiv");
20     var new_div = document.getElementById("wrap");
21     obj_btn.onclick = popup;
22     obj_link.onclick = function() {
23         obj_div.style.display = "none";
24         new_div.parentNode.removeChild(new_div);
25     };
26     function popup() {
27         obj_div.style.display = "block";
28         obj_div.style.top = document.documentElement.clientHeight/2 - obj_div.offsetHeight/2 + "px";
29         obj_div.style.left = document.documentElement.clientWidth/2 - obj_div.offsetWidth/2 + "px";
30         new_div = document.createElement("div");
31         new_div.setAttribute("id","wrap");
32         document.body.appendChild(new_div);
33         new_div.style.height = document.body.offsetHeight + "px";
34     }
35     window.onscroll = function() {
36         obj_div.style.top = document.documentElement.clientHeight/2 - obj_div.offsetHeight/2 + document.documentElement.scrollTop + document.body.scrollTop + "px";
37     };
38     window.onresize = function() {
39         obj_div.style.top = document.documentElement.clientHeight/2 - obj_div.offsetHeight/2 + "px";
40         obj_div.style.left = document.documentElement.clientWidth/2 - obj_div.offsetWidth/2 + "px";
41     };
42     document.onclick = function(e) {
43         if(!e) {var e = window.event;}
44         if(e.srcElement) {
45             var a = e.srcElement.getAttribute("id");
46         }
47         else {
48             var a = e.target.getAttribute("id");
49         }
50         if(a!=="popup" && a!=="btn") {
51             obj_div.style.display = "none";
52             new_div.parentNode.removeChild(new_div);
53         }
54     }
55     </script>
56 </body>
57 </html>
posted @ 2012-05-04 11:36  长风freedom  阅读(733)  评论(0编辑  收藏  举报