新聞中心
在pc端開發(fā),模態(tài)框是一個(gè)很常用的插件,之前一直用的第三方插件,比如bootstrap,jQuery的模態(tài)框插件,最近還用了elementUI的。但是會(huì)發(fā)現(xiàn)其實(shí)動(dòng)畫效果都差不多,那么如何去實(shí)現(xiàn)這樣一個(gè)動(dòng)畫效果呢?
創(chuàng)新互聯(lián)是一家專業(yè)提供譙城企業(yè)網(wǎng)站建設(shè),專注與成都網(wǎng)站設(shè)計(jì)、網(wǎng)站制作、成都h5網(wǎng)站建設(shè)、小程序制作等業(yè)務(wù)。10年已為譙城眾多企業(yè)、政府機(jī)構(gòu)等服務(wù)。創(chuàng)新互聯(lián)專業(yè)的建站公司優(yōu)惠進(jìn)行中。
模態(tài)框的構(gòu)成
常見的模態(tài)框的結(jié)構(gòu)我們很容易就可以看出,一個(gè)遮罩層,還有內(nèi)容區(qū)。內(nèi)容區(qū)主要是頭部(包括標(biāo)題,關(guān)閉按鈕)和body部分(body中常常會(huì)有確認(rèn)和取消按鈕)。
布局
1.背景要充滿全屏,而且如果頁面有滾動(dòng),當(dāng)模態(tài)框彈出的時(shí)候是無法滾動(dòng)的;
2.內(nèi)容區(qū)要水平居中顯示,至于垂直方向看設(shè)計(jì)嘍;
3.模態(tài)框出現(xiàn)是漸漸顯示出來,而且從頂部滑下;
實(shí)現(xiàn)
遮罩使用最外層元素占滿全屏(position:fixed;),并設(shè)置背景色不透明度(rgba(0,0,0,0.5))。
水平居中有很多方式,這里使用
margin:30px auto;
重點(diǎn)介紹下關(guān)于模態(tài)框動(dòng)畫的實(shí)現(xiàn)
關(guān)于漸漸顯示使用opacity就可以,而從頂部滑下使用translate也很容易實(shí)現(xiàn)。這么看來,很容易做嘛,只需要改變classname就可以了。
html
this is dialog title
×this is dialog content
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 h4,.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"; });
是不是看起來很容易,運(yùn)行之后,誒?并沒有我們所希望看到的動(dòng)畫效果,這是為什么呢?當(dāng)我們點(diǎn)擊按鈕的時(shí)候不是已經(jīng)把動(dòng)畫加上了么?
其實(shí)仔細(xì)想想,點(diǎn)擊按鈕改變classname的時(shí)候,是一下子把元素display和動(dòng)畫屬性全都加上了,當(dāng)模態(tài)框顯示出來的時(shí)候動(dòng)畫也隨著完成了,就類似于打開一個(gè)html頁面一樣,頁面元素的css屬性都在頁面渲染的時(shí)候發(fā)揮了作用。而我們?cè)陧撁嬷苯尤ビ|發(fā)一個(gè)已經(jīng)顯示出來的元素動(dòng)畫的時(shí)候是有效的。所以我們需要把元素顯示和動(dòng)畫分開來做。
這里我做了一個(gè)異步操作(setTimeout)。
oModal.style.display = "block"; var timer = setTimeout(function(){ oModal.className = "modal in"; clearTimeout(timer); },0);
元素顯示出來之后在給它加動(dòng)畫效果,這樣就可以實(shí)現(xiàn)我們所期望的動(dòng)畫效果了。
所有代碼在github上https://github.com/Stevenzwzhai/plugs/tree/master/dialog,在這個(gè)項(xiàng)目下有多個(gè)js的常用插件,歡迎點(diǎn)贊。
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。
本文題目:js實(shí)現(xiàn)類bootstrap模態(tài)框動(dòng)畫
網(wǎng)站地址:http://ef60e0e.cn/article/pdeois.html