javascript网页弹出层练习
网页中经常出现很多"popup"弹窗效果,这里做一个练习,给我们初学者一个参考。
HTML代码:
<div id="popup"></div> <a id="test" href="javascript:viod(0);">弹窗1</a> <a id="test1" href="javascript:viod(0);">弹窗2</a> <div id="box1" class="popbox"></div>
CSS代码:
*{padding:0; margin:0} #popup{position:fixed; width:100%; height:100%; z-index:888; background:#666; filter:alpha(opacity=60); opacity: 0.6; display:none;}/*遮罩层样式*/ .popbox{position:absolute; display:none; padding:10px; border:5px #e2e2e2 solid; background:#FFF; width:400px; height:300px; z-index:995; left:50%; top:50%;}/*弹出层样式*/
下面是JS代码,代码不精简,可以作为初学者参考哈:
function popup(obj,wd,ht){ var Width=400,Height=300;//设置一个默认的宽高 Obj=document.getElementById(obj); if(wd!=undefined)//下面是判断有没有设置宽高参数时的宽高取值 { Obj.style.width=wd+"px"; } if(ht!=undefined) { Obj.style.height=ht+"px"; } else if(wd!=undefined&&ht!=undefined) { Obj.style.width=wd+"px"; Obj.style.height=ht+"px"; } else{ Obj.style.width=Width+"px"; Obj.style.height=Height+"px"; } //添加关闭按钮和样式 var closeNode=document.createElement("a"); var Text=document.createTextNode("x"); closeNode.style.position="absolute"; closeNode.style.zIndex="999"; closeNode.style.right="7px"; closeNode.style.top="7px"; closeNode.style.color="#666666"; closeNode.style.padding="0 2px"; closeNode.style.background="#e2e2e2"; closeNode.style.cursor="pointer"; closeNode.appendChild(Text); document.getElementById("popup").style.display="block"; Obj.style.display="block"; Obj.style.marginLeft=-Obj.offsetWidth/2+"px";//计算水平居中 Obj.style.marginTop=-Obj.offsetHeight/2+"px";//计算垂直居中 Obj.appendChild(closeNode); closeNode.onclick=function(){ Obj.style.display="none"; document.getElementById("popup").style.display="none"; } } document.getElementById("test").onclick=function(){popup("box1");}//调用1 document.getElementById("test1").onclick=function(){popup("box1","300","150");}//调用2