1.代碼
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta http-equiv="content-Type" charset="UTF-8"> <meta http-equiv="x-ua-compatible" content="IE=edge"> <title>Title</title> <style> .cover{ position: fixed; /*首先將位置固定住*/ top:0; right:0; bottom:0; left:0; /*上下左右設置都爲0*/ background-color: rgba(0,0,0,0.2); z-index:99; /*指定一個元素的堆疊順序,數值越大,表示在越上邊*/ } .modal{ width:700px; height:400px; position: absolute; top:50%; left:50%; margin-left: -350px; margin-top: -200px; background-color: white; z-index: 100; /*將x的位置移動*/ } .close{ float: right; /*在這裏將x移動到右上角*/ margin-right: 15px; margin-top: 10px; font-size: 16px; } .hide{ display: none; /*表示不顯示*/ } </style> </head> <body> <button id="b1">點我彈出</button> <div class="cover hide" ></div> <!--這個標籤經過設置CSS樣式,將button及下層的東西蓋住,好比註冊登陸窗口的彈出就須要這個--> <!--hide表示不顯示這個div標籤,注意這個hide寫在class裏邊--> <div class="modal hide" > <span class="close" id="s1">×</span> <!--×表示x的意思,也能夠直接寫x--> </div> <script> // 思考如何實現,在點擊彈出按鈕以後,彈出兩個標籤 //首先,找標籤,注意這個地方是經過id處理的 var b1Ele=document.getElementById('b1') //其次,處理事件,單擊button以後,找到類屬性,移除類列表中的隱藏屬性 b1Ele.onclick=function (ev) { document.getElementsByClassName('cover')[0].classList.remove('hide'); document.getElementsByClassName('modal')[0].classList.remove('hide'); //移除樣式 } var s1Ele=document.getElementById('s1') //其次,處理事件,單擊button以後,找到類屬性,添加類列表中的隱藏屬性 s1Ele.onclick=function (ev) { document.getElementsByClassName('cover')[0].classList.add('hide'); document.getElementsByClassName('modal')[0].classList.add('hide'); //移除樣式 } </script> </body> </html> <!--目的就是:一點添加,一點關閉,這樣的操做-->
代碼效果:html
(1)運行ide
(2)點擊"點我彈出",結果以下圖ui
(3)再點擊x,回到界面(1)的效果,能夠反覆嘗試spa