彈出層效果的製作

    彈出層,就是點擊頁面的某個按鈕之後彈出一個覆蓋原來的層,一般運用在用戶登錄註冊上比較多。下面簡單的寫下實現原理:


1.首先是也面固有的狀態,這裏只是一個簡單的例子。
<pre name="code" class="html"><span style="font-size:18px;"><body>
<div id="header">
<button id="heder-login">登錄</button>
</div>
<div id="main">
<img src="img/index_banner01.jpg" />
<img src="img/index_banner01.jpg" />
</div>
<!-- 這裏註釋的部分實際上是需要通過JS來動態生成的部分,寫在這裏主要是爲了寫JS的時候更方便-->
<!--	 <div id="mask">
<div id="login">
<div class="loginCon"></div>
<div id="close"></div>
</div>
</div> 	   -->
</body></span>

下面是樣式部分:

<span style="font-family: 漢儀南宮體簡, 'MS Sans Serif', sans-serif; font-size: 19px; widows: auto; background-color: rgb(255, 237, 196);"></span><pre name="code" class="html"><style>
*{
margin: 0;
padding: 0;
}
#header{
width: 100%;
height: 40px;
background-color: gray;
}
#heder-login{
position: absolute;
background-color: crimson;
right: 0;
display: inline-block;
height: 40px;
width: 60px;
clear: both;
}
//下面的選擇器的height和width屬性都是需要用js動態設置,這裏就先不設置。
#mask{
left: 0;
top: 0;
position: absolute;

background-color: #808080;
opacity: 0.85;
z-index: 1000;
}
#login{ 

position:fixed;
z-index:1001;
}
 	 .loginCon{ 
position:relative; 
width:670px;
height:380px;
background:url(img/loginBg.png) #2A2C2E center center no-repeat;
}
#close{ 
background:url(img/close.png) no-repeat; 
width:30px; 
height:30px; 
cursor:pointer; 
position:absolute; 
right:5px; 
top:15px; 

}
</style>



下面開始寫js了

<span style="font-size:18px;"><script>
</span><span style="font-size:24px;">function newOpen(){
//獲取頁面高度和寬度
var sHeight=document.body.scrollHeight;
var sWidth=document.body.scrollWidth;
//獲取頁面可見高度和寬度
var cHeight=document.documentElement.clientHeight;
var cWidth=document.documentElement.clientWidth;

//設置整個背景
var oMask=document.createElement("div");
oMask.id="mask";
oMask.style.width=cWidth+"px";
oMask.style.height=sHeight+"px";
document.body.appendChild(oMask);
//設置登錄框
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=cWidth/2-dWidth/2+"px";
oLogin.style.top=cHeight/2-dHeight/2+"px";
//點擊關閉按鈕
var oClose=document.getElementById("close");
//點擊登陸框以外的區域也可以關閉登陸框
oClose.οnclick=oMask.οnclick=function(){
document.body.removeChild(oLogin);
document.body.removeChild(oMask);
};

}
window.οnlοad=function(){
var denglu=document.getElementById("header-login");
denglu.οnclick=function(){
newOpen();
return false;
}

}

</script>
</span>


這樣一個彈出層的效果就完成了。彈出層基本全是用的絕對定位,這樣方便元素確定元素的顯示位置。而且由於要將登陸框顯示在最上層,還要用到z-index這個屬性,他是數值越高,優先級越高。還有一個就是爲了將登陸框定位在屏幕中央,且不隨滾動提條的滾動而變化,將它用position:fixed固定,並且它的left值和top值都是用屏幕的可視寬度和高度分別減登陸框的寬度和高度後除以2等到的。
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章