javascript網頁彈出層練習

網頁中常常出現不少"popup"彈窗效果,這裏作一個練習,給咱們初學者一個參考。javascript

HTML代碼:java

<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代碼:app

*{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代碼,代碼不精簡,能夠做爲初學者參考哈:spa

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

相關文章
相關標籤/搜索