js實現(xiàn)類bootstrap模態(tài)框動畫
在pc端開發(fā),模態(tài)框是一個很常用的插件,之前一直用的第三方插件,比如bootstrap,jQuery的模態(tài)框插件,最近還用了elementUI的。但是會發(fā)現(xiàn)其實動畫效果都差不多,那么如何去實現(xiàn)這樣一個動畫效果呢?
模態(tài)框的構成
常見的模態(tài)框的結構我們很容易就可以看出,一個遮罩層,還有內容區(qū)。內容區(qū)主要是頭部(包括標題,關閉按鈕)和body部分(body中常常會有確認和取消按鈕)。
布局
1.背景要充滿全屏,而且如果頁面有滾動,當模態(tài)框彈出的時候是無法滾動的;
2.內容區(qū)要水平居中顯示,至于垂直方向看設計嘍;
3.模態(tài)框出現(xiàn)是漸漸顯示出來,而且從頂部滑下;
實現(xiàn)
遮罩使用最外層元素占滿全屏(position:fixed;),并設置背景色不透明度(rgba(0,0,0,0.5))。
水平居中有很多方式,這里使用
margin:30px auto;
重點介紹下關于模態(tài)框動畫的實現(xiàn)
關于漸漸顯示使用opacity就可以,而從頂部滑下使用translate也很容易實現(xiàn)。這么看來,很容易做嘛,只需要改變classname就可以了。
html
<input type="button" value="click" id="btn">
<div class="modal" id="modal">
<div class="dialog">
<header class="dialog-header">
<h3>this is dialog title</h3>
<span id="close">×</span>
</header>
<div class="dialog-content">
this is dialog content
</div>
</div>
</div>
style
.modal{
position:fixed;
left:0;
right:0;
top:0;
bottom:0;
background-color:rgba(0,0,0,0.5);
display:none;
z-index:1050;
opacity:0;
transition: all .5s ease-out 0s;
}
.dialog{
width:500px;
height:300px;
position:relative;
box-shadow:0 5px 15px rgba(0,0,0,.5);
border-radius:10px;
background-color:#fff;
margin:30px auto;
transform: translate(0,-40%);
-webkit-transform: translate(0,-40%);
transition: all .5s ease-out 0s;
}
.dialog-header{
box-sizing:border-box;
border-bottom:1px solid #ccc;
}
.dialog-header h3,.dialog-header span{
display:inline-block;
}
.dialog-header span{
float:right;
margin-right:10px;
overflow: hidden;
line-height:58px;
cursor:default;
font-size:18px;
}
.in{
opacity: 1;
}
.in .dialog{
transform: translate(0,0);
-webkit-transform: translate(0,0);
}
js
var oBtn = document.getElementById("btn");
var oModal = document.getElementById("modal");
var oClose = document.getElementById("close");
oBtn.addEventListener("click", function(){
oModal.style.display = "block";
oModal.className = "modal in";
});
oClose.addEventListener("click", function(){
oModal.style.display = "none";
oModal.className = "modal";
});
是不是看起來很容易,運行之后,誒?并沒有我們所希望看到的動畫效果,這是為什么呢?當我們點擊按鈕的時候不是已經把動畫加上了么?
其實仔細想想,點擊按鈕改變classname的時候,是一下子把元素display和動畫屬性全都加上了,當模態(tài)框顯示出來的時候動畫也隨著完成了,就類似于打開一個html頁面一樣,頁面元素的css屬性都在頁面渲染的時候發(fā)揮了作用。而我們在頁面直接去觸發(fā)一個已經顯示出來的元素動畫的時候是有效的。所以我們需要把元素顯示和動畫分開來做。
這里我做了一個異步操作(setTimeout)。
oModal.style.display = "block";
var timer = setTimeout(function(){
oModal.className = "modal in";
clearTimeout(timer);
},0);
元素顯示出來之后在給它加動畫效果,這樣就可以實現(xiàn)我們所期望的動畫效果了。
所有代碼在github上,在這個項目下有多個js的常用插件,歡迎點贊。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
javascript數(shù)組的擴展實現(xiàn)代碼集合
非常不錯的javascript數(shù)據功能增強函數(shù)2008-06-06

