css 在JS setTimeout之后有一个模态淡入

ffscu2ro  于 2023-03-25  发布在  其他
关注(0)|答案(2)|浏览(92)

我已经得到了3秒后出现的模式框,以及设置为50%不透明度的黑色背景。现在框和背景只出现在3秒,我不太明白如何从3秒开始将不透明度从0%(0.0)到50%(0.5)。
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;
}

联森:

const modal = document.getElementById("myModal");

const span = document.querySelector(".close");

setTimeout(function () {
  modal.style.display = "flex";
}, 3000);

span.onclick = () => {
  modal.style.display = "none";
};
wbgh16ku

wbgh16ku1#

使用动画绕过显示为无的项

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>
dgsult0t

dgsult0t2#

试试这个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名称

相关问题