html - 使用纯 CSS 将淡入淡出过渡添加到基于类的 div
问题描述
我有一个简单的警报框样式,其中包含一个关闭警报框的可点击按钮。代码如下所示:
.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
课程中添加了一些过渡,但没有明显的区别。
注意:警报框在隐藏时需要停止占用空间。所以能见度是行不通的。
解决方案
.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,无论页面是否完全加载,动画都会播放。您可以设置动画延迟,但您确实需要 javacsript 以确保在开始制作动画之前一切准备就绪。