JavaScript弹出层

1.这个弹出层就是一个DIV

2.看需要什么效果

  2.1.如果是仅仅需要弹出层,而背后的网页同样可以点击,那么只需要一个DIV即可,效果如图:

       

    2.2.需要一层透明背景,而后面的网页只能看不能点,效果如图:

   像这种,就需要至少两个DIV,一个负责显示中间的小部分,另一个DIV就负责显示后台灰色半透明的层。

这里有一个第二种情况的例子:

 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=gbk" />
 5 <title>无标题文档</title>
 6 <style type="text/css">
 7 /*弹出层的STYLE*/
 8 html,body {height:100%; margin:0px; font-size:12px;}
 9 
10 
11 
12 .mydiv {
13 /*就是这个position:fixed起作用,生成相对定位的元素,相对于其正常位置进行定位。*/
14      position:fixed;
15 
16      /*这里都是对外边距进行设置*/
17      margin:auto;
18      left:0;
19      right:0;
20      top:0; 
21      bottom:0;
22      z-index:99;
23      line-height: 40px;
24      padding-left:20px;
25      
26       /*设置div的宽和高*/
27      width:500px; 
28      height:180px;
29 
30      
31 background-color: #ffa;
32 border: 1px solid #f90;
33 }
34 
35 .bg {
36 line-height: 40px;
37 background-color: #ccc;
38 width: 100%;
39 height: 100%;
40 left:0;
41 top:0;/*FF IE7*/
42 filter:alpha(opacity=50);/*IE*/
43 opacity:0.5;/*FF*/
44 z-index:1;
45 
46 position:fixed!important;/*FF IE7*/
47 position:absolute;/*IE6*/
48 
49 _top:       expression(eval(document.compatMode &&
50             document.compatMode=='CSS1Compat') ?
51             documentElement.scrollTop + (document.documentElement.clientHeight-this.offsetHeight)/2 :/*IE6*/
52             document.body.scrollTop + (document.body.clientHeight - this.clientHeight)/2);/*IE5 IE5.5*/
53 
54 }
55 
56 /*The END*/
57 
58 </style>
59 <script type="text/javascript">
60 function showDiv(){
61 document.getElementById('popDiv').style.display='block';
62 document.getElementById('bg').style.display='block';
63 }
64 
65 function closeDiv(){
66 document.getElementById('popDiv').style.display='none';
67 document.getElementById('bg').style.display='none';
68 }
69 
70 </script>
71 </head>
72 
73 <body>
74 <!--这里其实要用到两个弹出层,一个是我们要显示的内容,一个是后面透明的背景-->
75 <div id="popDiv" class="mydiv" style="display:none;">恭喜你!<br/>你的成绩为:60分<br/>
76 <a href="javascript:closeDiv()">关闭窗口</a></div>
77 <!--就是这个透明的背景-->
78 <div id="bg" class="bg" style="display:none;"></div>
79 
80  
81 
82 <div style="padding-top: 20px;">
83 <input type="Submit" name="" value="显示层" onclick="javascript:showDiv()" />
84 </div>
85 </body>
86 </html>
View Code
原文地址:https://www.cnblogs.com/tommy-huang/p/4335746.html