1. 程式人生 > 實用技巧 >做一個彈窗

做一個彈窗

起因

在京東面試時面試官問我如何實現一個彈框,我答了z-index;看來要複習一下了;

基礎知識

css中z-index層級

思路

1.先用一個div蒙塵罩罩住最低下的東西;
2.在div蒙塵罩中間放一個div用於寫彈框內的東西;
3.用display或visibility控制顯示隱藏;

主要程式碼

    <style>
    /* html,body{
        width: 100%;
        height: 100%;
    } */
  *{
      padding: 0px;
      margin:0px;
  }
   body{
       background:purple ;

   }
   h1{
       position: absolute;
       z-index: 0;
   }
   .cover{
       position: absolute;
       z-index: 1;
       width: 100%;
       height: 100%;
       background: rgb(163, 159, 159,0.5);
       display: none;
       justify-content: center;
       align-items: center;
   }
   .box{
    position: absolute;
       z-index:2;
       width: 200px;
       height: 200px;
       background: yellow;
   }
   #open{
       position: absolute;
       left:100px;
   }
    </style>
<body>
    <div class="all">
        <h1>我是主頁</h1>
        <button id="open">開啟彈窗</button>
    </div>
    <div class="cover" id="cover">
      <div class="box">
          我是彈窗
          <button id="close">關閉彈窗</button>
      </div>
    </div>
    <script>
        var btnOpen=document.getElementById("open");
        var btnClose=document.getElementById("close");
        var box=document.getElementById("cover");
        btnOpen.onclick=function(){
            box.style.display="flex";
            console.log("打開了");
        }
        btnClose.onclick=function(){
            box.style.display="none";
            console.log("關了");
        }

    </script>
</body>

效果展示


遇到問題

  1. z-index必須要改變position值才能生效(position不為static)
    position設定為static時(預設),z-index和四個方位對其都無效;
  2. 關於div無元素時的撐開:
/*1.給div設定position*/
  css中position有五種屬性: static:預設值,沒有定位;absolute:絕對定位,相對於父級元素進行定位;relative:相對定位;fixed:固定定位,相對於瀏覽器視窗進行定位;inherit:從父元素繼承定位資訊;除了預設值static和inherit之外,新增其他三種都可以實現視窗自適應。
/*2.給html,body設定寬高來讓div繼承*/
2         *{
 3             margin: 0;
 4             padding: 0;
 5         }
 6         html,body{
 7             width: 100%;
 8             height: 100%;
 9         }
10         div{
11             width:100%;
12             height: 100%;
13             background: yellow;
14         }