css實現彈出框


彈出框也是前端里面經常使用的一個應用場景了,最開始想到的是用js實現這個效果,看到codepen上面有用css實現的。其實就是用到了css里面的一個:target選擇器+visibility屬性。

URL 帶有后面跟有錨名稱 #,指向文檔內某個具體的元素。這個被鏈接的元素就是目標元素(target element)。:target 選擇器可用於選取當前活動的目標元素。

示例代碼:

<div class="container">
  <a href="#popup" class="button">刪除</a>
  <div class="popup" id="popup">
    <div class="popup-inner">
      <div class="popup__text">
        <h3>刪除寶貝</h3>
        <p>確定要刪除該寶貝嗎?</p>
        <p><span><a href="javascript:void(0)">確定</a></span><span><a href="#">關閉</a></span></p>
      </div>
      <a href="#" class="popup__close">&times;</a>
    </div>
  </div>
</div>

scss代碼:
$main-color: #9191E9;

* {
  box-sizing: border-box;
  padding: 0;
  margin: 0;
}

html, body {
  font-family: 'Raleway', sans-serif;
  font-size: 16px;
}

.container {
  background-color: $main-color;
  display: flex;
  align-items: center;
  justify-content: center;
  width: 100vw;
  height: 100vh;
}

.button {
  text-decoration: none;
  font-size: .875rem;
}

.popup {
  display: flex;
  align-items: center;
  justify-content: center;
  position: fixed;
  bottom: 0;
  right: 0;
  width: 100vw;
  height: 100vh;
  z-index: 2;
  visibility: hidden;
  &-inner {
    background-color: #fff;
    width: 400px;
    height: 180px;
    display: flex;
    align-items: center;
    position: relative;
    bottom: -100vw;
    right: -100vh;
    transform: rotate(32deg);
    transition: .64s ease-in-out;
  }
  &__text {
    padding: 2rem;
    h3 {
      font-size: 1.2rem;
      font-weight: 600;
      margin-bottom: 1.2rem;
    }
    p {
      font-size: .75rem;
      margin-top: 1rem;
    }
    span {
      display: inline-block;
      padding: .42rem 1rem;
      margin-right: .625rem;
      a {
        text-decoration: none;
      }
      &:first-child {
        background-color: #52A0E5;
        border: 1px solid #52A0E5;
        a {
          color: white;
          &:hover {
            text-decoration: underline;
          }
        }
      }
      &:last-child {
        border: 1px solid grey;
        a {
          color: grey;
          &:hover {
            color: red;
            text-decoration:underline;
          }
        }
      }
    }
  }
  &__close {
    position: absolute;
    right: 1.8rem;
    top: 1.8rem;
    font-size: 1.5rem;
    color: grey;
    text-decoration: none;
    font-weight: 800;
  }
  &:target {
    visibility: visible;
    .popup-inner {
      bottom: 0;
      right: 0;
      transform: rotate(0);
    }
  }
}

scss代碼有點略長,核心就是.popup:targetvisibility的結合,為什么不用opcaity和display呢?在這個場景中,opacity會影響html頁面里的錨(這里面的popup遮擋到了body里面的a標簽),而display不支持transition,並使transition失效。這里為了讓彈出框不那么突兀地出現,加了一個小小的動畫效果。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM