js动态添加Div

利用JavaScript动态添加Div的方式有很多,在这次开发中有用到,就搜集了一下比较常用的。

一、在一个Div前添加Div

<html>
  <body>
  <div   id="a">   
   <div   id="a1">1</div> 
   <div   id="a2">2</div>   
  </div>   
        <a href="javascript:addDiv();">test</a>                          
  </body>
<script   type="text/javascript">   
 function addDiv(){
        var   newNode=document.createElement("div");   
        newNode.setAttribute("id","a3");   
        var   txtNode=document.createTextNode("3");   
        newNode.appendChild(txtNode);   
          
        document.getElementById("a").insertBefore(newNode,document.getElementById("a2"));   
          
        alert(document.getElementById("a").innerHTML)   
}
 </script>   
</html>
View Code

二、动态添加Div,并在Div上添加事件

<html>
 <body>
   <a href="javascript:aa();">text</a> 
 </body>
</html>
<script language=javascript>
        var divId=1;
        //动态生成单纯的div
        function CreateOuterDiv()
        {
            var obj=document.createElement("div");
            obj.id="myDiv"+divId;
            divId++;
            obj.style.border="1px solid #000000";
            obj.style.height="30px";
            obj.style.width="200px";
            obj.style.filter="alpha(opacity=70)";            
            obj.style.margin="10px";     
            obj.style.cursor="hand";
            obj.algin="center";       
            //obj.innerHTML="<a href='#"+obj.id+"'>ssssssssss</a>";
            obj.innerText="sssssss";
            
            document.body.appendChild(obj);          
            document.getElementById(obj.id).onclick=function(){aa();};            
        }
        function aa()
        {
            CreateOuterDiv();//alert();
        }   
</script>
View Code

三、动态添加Div,并删除某个Div

 1 <html xmlns="http://www.w3.org/1999/xhtml">
 2 <head>
 3 <meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
 4 <title>无标题文档</title>
 5 </head>
 6     <script type="text/javascript">
 7     var a=0;
 8     function add(){
 9         var o=document.getElementById("PhotoLabel");
10         var div=document.createElement("div");
11         div.id = div.name = "d"+ a;  
12         div.innerHTML=o.innerHTML.replace(/{0}/ig,a);
13         document.getElementById("addPhotoLabel").appendChild(div);
14         //document.write(document.getElementById("addPhotoLabel").innerHTML);
15         alert(document.getElementById("addPhotoLabel").innerHTML);
16         a++;
17     }
18     //window.onload =  function(){add();}
19     function deleteDiv(){
20      var oDiv= document.getElementById("d2");
21       document.getElementById("addPhotoLabel").removeChild(oDiv); 
22     }
23     </script>
24 <body>
25 <div id="PhotoLabel">
26 safasfdgdag
27 <a>aasscc</a>
28 </div>
29 <div id="addPhotoLabel"></div>
30 <a href="javascript:add();"><span style="font-size: 15px">增加</span></a>
31 <a href="javascript:deleteDiv();"><span style="font-size: 15px">删除第二个</span></a>
32 </body>
33 </html>
View Code

四、弹出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=gb2312" />
  5 <title>JavaScript 仿LightBox内容显示效果</title>
  6 </head>
  7 
  8 <body>
  9 
 10 <br /><br /><br /><br />
 11 
 12 
 13 
 14 <script>
 15 
 16 var isIE = (document.all) ? true : false;
 17 
 18 var isIE6 = isIE && ([/MSIE (d).0/i.exec(navigator.userAgent)][0][1] == 6);
 19 
 20 var $ = function (id) {
 21     return "string" == typeof id ? document.getElementById(id) : id;
 22 };
 23 
 24 var Class = {
 25     create: function() {
 26         return function() { this.initialize.apply(this, arguments); }
 27     }
 28 }
 29 
 30 var Extend = function(destination, source) {
 31     for (var property in source) {
 32         destination[property] = source[property];
 33     }
 34 }
 35 
 36 var Bind = function(object, fun) {
 37     return function() {
 38         return fun.apply(object, arguments);
 39     }
 40 }
 41 
 42 var Each = function(list, fun){
 43     for (var i = 0, len = list.length; i < len; i++) { fun(list[i], i); }
 44 };
 45 
 46 var Contains = function(a, b){
 47     return a.contains ? a != b && a.contains(b) : !!(a.compareDocumentPosition(b) & 16);
 48 }
 49 
 50 
 51 var OverLay = Class.create();
 52 OverLay.prototype = {
 53   initialize: function(options) {
 54 
 55     this.SetOptions(options);
 56     
 57     this.Lay = $(this.options.Lay) || document.body.insertBefore(document.createElement("div"), document.body.childNodes[0]);
 58     
 59     this.Color = this.options.Color;
 60     this.Opacity = parseInt(this.options.Opacity);
 61     this.zIndex = parseInt(this.options.zIndex);
 62     
 63     with(this.Lay.style){ display = "none"; zIndex = this.zIndex; left = top = 0; position = "fixed"; width = height = "100%"; }
 64     
 65     if(isIE6){
 66         this.Lay.style.position = "absolute";
 67         //ie6设置覆盖层大小程序
 68         this._resize = Bind(this, function(){
 69             this.Lay.style.width = Math.max(document.documentElement.scrollWidth, document.documentElement.clientWidth) + "px";
 70             this.Lay.style.height = Math.max(document.documentElement.scrollHeight, document.documentElement.clientHeight) + "px";
 71         });
 72         //遮盖select
 73         this.Lay.innerHTML = '<iframe style="position:absolute;top:0;left:0;100%;height:100%;filter:alpha(opacity=0);"></iframe>'
 74     }
 75   },
 76   //设置默认属性
 77   SetOptions: function(options) {
 78     this.options = {//默认值
 79         Lay:        null,//覆盖层对象
 80         Color:        "#fff",//背景色
 81         Opacity:    50,//透明度(0-100)
 82         zIndex:        1000//层叠顺序
 83     };
 84     Extend(this.options, options || {});
 85   },
 86   //显示
 87   Show: function() {
 88     //兼容ie6
 89     if(isIE6){ this._resize(); window.attachEvent("onresize", this._resize); }
 90     //设置样式
 91     with(this.Lay.style){
 92         //设置透明度
 93         isIE ? filter = "alpha(opacity:" + this.Opacity + ")" : opacity = this.Opacity / 100;
 94         backgroundColor = this.Color; display = "block";
 95     }
 96   },
 97   //关闭
 98   Close: function() {
 99     this.Lay.style.display = "none";
100     if(isIE6){ window.detachEvent("onresize", this._resize); }
101   }
102 };
103 
104 
105 
106 var LightBox = Class.create();
107 LightBox.prototype = {
108   initialize: function(box, options) {
109     
110     this.Box = $(box);//显示层
111     
112     this.OverLay = new OverLay(options);//覆盖层
113     
114     this.SetOptions(options);
115     
116     this.Fixed = !!this.options.Fixed;
117     this.Over = !!this.options.Over;
118     this.Center = !!this.options.Center;
119     this.onShow = this.options.onShow;
120     
121     this.Box.style.zIndex = this.OverLay.zIndex + 1;
122     this.Box.style.display = "none";
123     
124     //兼容ie6用的属性
125     if(isIE6){
126         this._top = this._left = 0; this._select = [];
127         this._fixed = Bind(this, function(){ this.Center ? this.SetCenter() : this.SetFixed(); });
128     }
129   },
130   //设置默认属性
131   SetOptions: function(options) {
132     this.options = {//默认值
133         Over:    true,//是否显示覆盖层
134         Fixed:    false,//是否固定定位
135         Center:    false,//是否居中
136         onShow:    function(){}//显示时执行
137     };
138     Extend(this.options, options || {});
139   },
140   //兼容ie6的固定定位程序
141   SetFixed: function(){
142     this.Box.style.top = document.documentElement.scrollTop - this._top + this.Box.offsetTop + "px";
143     this.Box.style.left = document.documentElement.scrollLeft - this._left + this.Box.offsetLeft + "px";
144     
145     this._top = document.documentElement.scrollTop; this._left = document.documentElement.scrollLeft;
146   },
147   //兼容ie6的居中定位程序
148   SetCenter: function(){
149     this.Box.style.marginTop = document.documentElement.scrollTop - this.Box.offsetHeight / 2 + "px";
150     this.Box.style.marginLeft = document.documentElement.scrollLeft - this.Box.offsetWidth / 2 + "px";
151   },
152   //显示
153   Show: function(options) {
154     //固定定位
155     this.Box.style.position = this.Fixed && !isIE6 ? "fixed" : "absolute";
156 
157     //覆盖层
158     this.Over && this.OverLay.Show();
159     
160     this.Box.style.display = "block";
161     
162     //居中
163     if(this.Center){
164         this.Box.style.top = this.Box.style.left = "50%";
165         //设置margin
166         if(this.Fixed){
167             this.Box.style.marginTop = - this.Box.offsetHeight / 2 + "px";
168             this.Box.style.marginLeft = - this.Box.offsetWidth / 2 + "px";
169         }else{
170             this.SetCenter();
171         }
172     }
173     
174     //兼容ie6
175     if(isIE6){
176         if(!this.Over){
177             //没有覆盖层ie6需要把不在Box上的select隐藏
178             this._select.length = 0;
179             Each(document.getElementsByTagName("select"), Bind(this, function(o){
180                 if(!Contains(this.Box, o)){ o.style.visibility = "hidden"; this._select.push(o); }
181             }))
182         }
183         //设置显示位置
184         this.Center ? this.SetCenter() : this.Fixed && this.SetFixed();
185         //设置定位
186         this.Fixed && window.attachEvent("onscroll", this._fixed);
187     }
188     
189     this.onShow();
190   },
191   //关闭
192   Close: function() {
193     this.Box.style.display = "none";
194     this.OverLay.Close();
195     if(isIE6){
196         window.detachEvent("onscroll", this._fixed);
197         Each(this._select, function(o){ o.style.visibility = "visible"; });
198     }
199   }
200 };
201 
202 </script>
203 
204 
205 <style>
206 .lightbox{width:300px;background:#FFFFFF;border:1px solid #ccc;line-height:25px; top:20%; left:20%;}
207 .lightbox dt{background:#f4f4f4; padding:5px;}
208 </style>
209 
210 <dl id="idBox" class="lightbox">
211   <dt id="idBoxHead"><b>LightBox</b> </dt>
212   <dd>
213     内容显示
214     <br /><br />
215     <input name="" type="button" value=" 关闭 " id="idBoxCancel" />
216     <br /><br />
217   </dd>
218 </dl>
219 
220 
221 <div style="margin:0 auto; 900px; height:1000px; border:1px solid #000000;">
222 
223 <input type="button" value="关闭覆盖层" id="btnOverlay" />
224 <input type="button" value="黑色覆盖层" id="btnOverColor" />
225 <input type="button" value="全透覆盖层" id="btnOverOpacity" />
226 <input type="button" value="定位效果" id="btnFixed" />
227 <input type="button" value="居中效果" id="btnCenter" />
228 <br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br /><br />
229 <select>
230 <option>覆盖select测试</option>
231 </select> 
232 <input name="" type="button" value=" 打开 " id="idBoxOpen" />
233 
234 </div>
235 
236 
237 
238 <script>
239 
240 var box = new LightBox("idBox");
241 
242 $("idBoxCancel").onclick = function(){ box.Close(); }
243 $("idBoxOpen").onclick = function(){ box.Show(); }
244 
245 $("btnOverlay").onclick = function(){
246     box.Close();
247     if(box.Over){
248         box.Over = false;
249         this.value = "打开覆盖层";
250     } else {
251         box.Over = true;
252         this.value = "关闭覆盖层";
253     }
254 }
255 
256 $("btnOverColor").onclick = function(){
257     box.Close();
258     box.Over = true;
259     if(box.OverLay.Color == "#fff"){
260         box.OverLay.Color = "#000";
261         this.value = "白色覆盖层";
262     } else {
263         box.OverLay.Color = "#fff"
264         this.value = "黑色覆盖层";
265     }
266 }
267 
268 $("btnOverOpacity").onclick = function(){
269     box.Close();
270     box.Over = true;
271     if(box.OverLay.Opacity == 0){
272         box.OverLay.Opacity = 50;
273         this.value = "全透覆盖层";
274     } else {
275         box.OverLay.Opacity = 0;
276         this.value = "半透覆盖层";
277     }
278 }
279 
280 $("btnFixed").onclick = function(){
281     box.Close();
282     if(box.Fixed){
283         box.Fixed = false;
284         this.value = "定位效果";
285     } else {
286         box.Fixed = true;
287         this.value = "取消定位";
288     }
289 }
290 
291 $("btnCenter").onclick = function(){
292     box.Close();
293     if(box.Center){
294         box.Center = false;
295         box.Box.style.left = box.Box.style.top = "20%";
296         box.Box.style.marginTop = box.Box.style.marginLeft = "0";
297         this.value = "居中效果";
298     } else {
299         box.Center = true;
300         this.value = "重新定位";
301     }
302 }
303 </script>
304 
305 </body>
306 </html>
View Code
原文地址:https://www.cnblogs.com/lanye/p/3359087.html