如何为 CSS ::backdrop 在 HTML <dialog> 后面设置动画?

How to animate CSS ::backdrop behind HTML <dialog>?

<dialog> 元素现在跨浏览器兼容(自 March 2022)。

我今天试了一下,熟悉了:

一切看起来都很简单,但到目前为止我无法实现的一件事是:淡化背景

例如,如果我希望背景的最终颜色为:

但是 transition(或 animate)到 background-color 来自:

这可能吗?


这是我的(非工作)示例:

const myButton = document.querySelector('button');
const myDialog = document.querySelector('dialog');

const requestDialog = () => {
  myDialog.showModal();
  setTimeout(() => myDialog.classList.add('fadeUp'), 400);
}

myButton.addEventListener('click', requestDialog, false);
body {
  display: flex;
  justify-content: center;
  align-items: center;
  height: 180px;
}

button {
  position: absolute;
  top: 6px;
  left: 6px;
  cursor: pointer;
}

dialog::backdrop {
  background-color: rgba(0, 0, 0, 0);
  transition: backgroundColor 0.6s ease-out;
}

dialog.fadeUp::backdrop {
  background-color: rgba(0, 0, 63, 0.8);
}
<button type="button">Click me to<br />Request Dialog</button>

<dialog>
  <h2>My Dialog</h2>
</dialog>

如果您使用 box-shadow,它可能会起作用并且足够接近您尝试做的事情:

dialog {
   box-shadow: 0 0 0 100vw rgba(0, 0, 0, 0);
   transition:  2s ease-out;
 }  
dialog.fadeUp {
   box-shadow: 0 0 0 100vw  rgba(0, 0, 63, 0.8);
   transition:  2s ease-out;
 }

我遇到了同样的问题,但这解决了我的问题。

const dialog = document.querySelector('.modal')

function openModal() {
  dialog.showModal(); // default dialog method
}

function closeModal() {
  dialog.classList.add('close'); // run animation here
  
  dialog.addEventListener('animationend', () => {
    dialog.classList.remove('close')
    dialog.close(); // then run the default close method
  }, {once : true}); // add this to prevent bugs when reopening the modal
}
.modal {
  display: none;
}
/* when the dialog is open by its default method it adds a open tag on the element */
.modal[open] {
  display: flex;
}

.modal[open]::backdrop {
  animation: backdrop-fade 2s  ease forwards;
}

.modal.close::backdrop {
  animation: backdrop-fade 3s ease backwards;
  animation-direction: reverse;
}

@keyframes backdrop-fade {
  from {
    background: transparent;
  }
  to{
    background: rgba(0,0,0);
  }
}
<button onclick="openModal()">open modal</button>
<dialog class="modal">
    <button onclick="closeModal()">close modal</button>
</dialog>

G-Cyrillus的回答近乎完美!刚刚在 box-shadow 中添加了 max 的使用,这样阴影就会覆盖在移动设备上。

box-shadow: 0 0 0 100vmax rgba(0, 0, 0, 0);