我在 3 秒后出现了模态框,黑色背景设置为 50% 不透明度。现在盒子和背景刚好在 3 秒时出现,我不太清楚如何让不透明度从 0% (0.0) 到 50% (0.5) 从 3 秒开始。
CSS:
.modal {
display: none;
position: fixed;
z-index: 999;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
justify-content: center;
align-items: center;
}
JS:
const modal = document.getElementById("myModal");
const span = document.querySelector(".close");
setTimeout(function () {
modal.style.display = "flex";
}, 3000);
span.onclick = () => {
modal.style.display = "none";
};
试试这个 CSS
#myModal {
display: none;
position: fixed;
z-index: 999;
width: 100%;
height: 100%;
background-color: rgba(0, 0, 0, 0.5);
justify-content: center;
align-items: center;
opacity: 1;
transition-property: opacity;
transition-duration: 5s;
transition-delay: 3s;
}
它会在不透明度中消失
这是您的代码的错误。你的 css 是一个类而不是一个 ID。所以,JS找不到触发的ID。
我将其更改为您 JS 中定义的 ID 名称
使用动画绕过正在显示的项目 none
document.querySelector("#btn").addEventListener("click", () => {
document.querySelector('.modal').classList.toggle("show");
});
.modal {
position: absolute;
left: 100px;
right: 100px;
width: 100px;
height: 100px;
border: 1px solid #000000;
opacity: 0;
background-color: #CCC;
display: none;
}
.modal.show {
display: block;
opacity: 1;
animation-name: showModal;
animation-iteration-count: 1;
animation-timing-function: ease-in;
animation-duration: 1s;
}
@keyframes showModal {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<div class="modal">
XXXXXXX
</div>
<button id="btn">click</button>