代码之家  ›  专栏  ›  技术社区  ›  darkhorse

基于使用纯css的类向div添加淡入淡出转换[duplicate]

  •  0
  • darkhorse  · 技术社区  · 6 年前

    这个问题已经有了答案:

    我有一个简单的警报框样式,其中包含一个可点击的按钮,关闭警报框。代码如下所示:

    .alert {
        position: relative;
        padding: 1.2rem 2rem;
        background-color: rgba(0, 0, 0, 0.01);
        border: 1px solid rgba(0, 0, 0, 0.1);
        border-radius: var(--border-radius);
    }
    
    .alert.hidden {
        display: none;
    }
    <div class="alert">
      This is an alert box.
      <button onclick="this.parentNode.classList.add('hidden')">Close</button>
    </div>
    
    <div class="alert">
      Another one
      <button onclick="this.parentNode.classList.add('hidden')">Close</button>
    </div>

    如您所见,单击按钮并添加 .hidden 类到父元素。如何为该事件添加一个简单的淡出?

    此外,我还想创建另一个类,如 .alert.fade-in 它将在第一页加载时淡入警告框。

    到目前为止,我在 .alert 但没有明显的区别。

    注意:警报框在隐藏时需要停止占用空间。所以能见度不起作用。

    1 回复  |  直到 6 年前
        1
  •  3
  •   MomasVII    6 年前

    .alert {
        position: relative;
        padding: 1.2rem 2rem;
        background-color: rgba(0, 0, 0, 0.01);
        border: 1px solid rgba(0, 0, 0, 0.1);
        border-radius: var(--border-radius);
    }
    
    .alert.hidden {
        animation:1s fadeMe forwards;
    }
    
    @keyframes fadeMe {
      0% { opacity:1; }
      99% { padding: 1.2rem 2rem; height:auto; }
      100% { opacity:0; height:0px; padding:0; }
    }
    <div class="alert">
      This is an alert box.
      <button onclick="this.parentNode.classList.add('hidden')">Close</button>
    </div>
    
    <div class="alert">
      Another one
      <button onclick="this.parentNode.classList.add('hidden')">Close</button>
    </div>

    至于页面加载时的淡入,使用css进行淡入是很棘手的,因为一旦加载css,动画就会播放页面是否已完全加载。您可以设置动画延迟,但在开始制作动画之前,您确实需要javacscript来确保一切就绪。