1. 程式人生 > >javascript實現彈層效果

javascript實現彈層效果

end 彈層 css樣式 posit .com nload script 代碼 ner

首先,需要有一個按鈕來模擬登錄:

<button id="btnLogin"class="login-btn">登錄</button>

技術分享圖片

然後呢,我們想通過點擊這個按鈕實現這樣一個效果:

技術分享圖片

從上面這張圖片,我們可以看到,灰色背景就是遮罩層,而淺藍色的區域就是登陸框位置所在了。OK,下面先看一下HTML結構和css樣式:

技術分享圖片
<div id="mask"></div>  //遮罩層
<div id="login">       //登陸框包裹層
      <div id="loginCon">  //表單內容
          <div id="close">點擊關閉</div>  //關閉按鈕
          我是登錄框喲!
      </div>
 </div>
技術分享圖片

這裏只是將HTML結構拿出來講一下,但是下面我們是通過JS來創建它們的,所以這裏只是為了方便我們理解,並不需要放在html文件裏。

CSS樣式:

技術分享圖片
#close{ 
    background:url(img/close.png) no-repeat; 
    width:30px; 
    height:30px; 
    cursor:pointer; 
    position:absolute; 
    right:5px; 
    top:5px; 
    text-indent:-999em;
    }
#mask{ 
    background-color:#ccc;
    opacity:0.7;
    filter: alpha(opacity=70); 
    position:absolute; 
    left:0;
    top:0;
    z-index:1000;
    }
#login{ 
    position:fixed;
    z-index:1001;
    }
.loginCon{ 
    position:relative; 
    width:670px;
    height:380px;
    background:lightblue;
    border:3px solid #333;
    text-align: center;
    }
技術分享圖片

css樣式中需要註意一下z-index屬性,因為我們需要讓遮罩層蓋住除了登錄框之外所有的頁面內容,所以,需要確保登錄框的層次最高,遮罩層次之,所以一般將這兩個的z-index屬性值設置為比較高的數值,但遮罩層要比登陸框少一層。然後還有一點就是遮罩層必須設置透明度,不然就太難看了,用戶體驗極其不好!

JS實現代碼:

技術分享圖片
function dialog(){
    //獲取頁面的高度和寬度
    var sWidth=document.body.scrollWidth || document.documentElement.scrollWidth;
    var sHeight=document.body.scrollHeight || document.documentElement.scrollHeight;
    
    //獲取頁面的可視區域高度和寬度
    var wHeight=document.documentElement.clientHeight || document.body.clientHeight;
    
                //創建遮罩層
    var oMask=document.createElement("div");
    oMask.id="mask";
    oMask.style.height=sHeight+"px";
    oMask.style.width=sWidth+"px";
    document.body.appendChild(oMask);            //添加到body末尾
      
               //創建登錄框
    var oLogin=document.createElement("div");
    oLogin.id="login";
    oLogin.innerHTML="<div class=‘loginCon‘><div id=‘close‘>點擊關閉</div>我是登錄框喲!</div>";
    document.body.appendChild(oLogin);
    
    //獲取登陸框的寬和高
    var dHeight=oLogin.offsetHeight;
    var dWidth=oLogin.offsetWidth;

    //設置登陸框的left和top
    oLogin.style.left=sWidth/2-dWidth/2+"px";
    oLogin.style.top=wHeight/2-dHeight/2+"px";

    //獲取關閉按鈕
    var oClose=document.getElementById("close");
    
    //點擊關閉按鈕和點擊登陸框以外的區域都可以關閉登陸框
    oClose.onclick=oMask.onclick=function(){
        document.body.removeChild(oLogin);
        document.body.removeChild(oMask);
    };
}
                    
window.onload=function(){
    var oBtn=document.getElementById("btnLogin");
    //點擊登錄按鈕
    oBtn.onclick=function(){
        dialog();
    }
                
}
技術分享圖片

這種方法是通過JS在事件綁定裏動態創建和移除這些標簽,然後設置他們的 id 和 style 屬性。

javascript實現彈層效果