您好,登錄后才能下訂單哦!
在pc端開發(fā),模態(tài)框是一個很常用的插件,之前一直用的第三方插件,比如bootstrap,jQuery的模態(tài)框插件,最近還用了elementUI的。但是會發(fā)現(xiàn)其實動畫效果都差不多,那么如何去實現(xiàn)這樣一個動畫效果呢?
模態(tài)框的構(gòu)成
常見的模態(tài)框的結(jié)構(gòu)我們很容易就可以看出,一個遮罩層,還有內(nèi)容區(qū)。內(nèi)容區(qū)主要是頭部(包括標(biāo)題,關(guān)閉按鈕)和body部分(body中常常會有確認(rèn)和取消按鈕)。
布局
1.背景要充滿全屏,而且如果頁面有滾動,當(dāng)模態(tài)框彈出的時候是無法滾動的;
2.內(nèi)容區(qū)要水平居中顯示,至于垂直方向看設(shè)計嘍;
3.模態(tài)框出現(xiàn)是漸漸顯示出來,而且從頂部滑下;
實現(xiàn)
遮罩使用最外層元素占滿全屏(position:fixed;),并設(shè)置背景色不透明度(rgba(0,0,0,0.5))。
水平居中有很多方式,這里使用
margin:30px auto;
重點介紹下關(guān)于模態(tài)框動畫的實現(xiàn)
關(guā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"> <h4>this is dialog title</h4> <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 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"; });
是不是看起來很容易,運行之后,誒?并沒有我們所希望看到的動畫效果,這是為什么呢?當(dāng)我們點擊按鈕的時候不是已經(jīng)把動畫加上了么?
其實仔細(xì)想想,點擊按鈕改變classname的時候,是一下子把元素display和動畫屬性全都加上了,當(dāng)模態(tài)框顯示出來的時候動畫也隨著完成了,就類似于打開一個html頁面一樣,頁面元素的css屬性都在頁面渲染的時候發(fā)揮了作用。而我們在頁面直接去觸發(fā)一個已經(jīng)顯示出來的元素動畫的時候是有效的。所以我們需要把元素顯示和動畫分開來做。
這里我做了一個異步操作(setTimeout)。
oModal.style.display = "block"; var timer = setTimeout(function(){ oModal.className = "modal in"; clearTimeout(timer); },0);
元素顯示出來之后在給它加動畫效果,這樣就可以實現(xiàn)我們所期望的動畫效果了。
所有代碼在github上https://github.com/Stevenzwzhai/plugs/tree/master/dialog,在這個項目下有多個js的常用插件,歡迎點贊。
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持億速云。
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。