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

Rou*_*ica 10 html javascript css dialog backdrop

<dialog>元素现已跨浏览器兼容(自2022 年 3 月起)。

我今天尝试了一下并熟悉了:

  • 超文本标记语言

    • <dialog>
  • JavaScript

    • .show()
    • .showModal()
    • .close()
  • CSS

    • ::backdrop

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

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

  • background-color: rgba(0, 0, 63, 0.8);

但有它transition(或animate)来自background-color

  • background-color: rgba(0, 0, 0, 0);

这可能吗?


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

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);
Run Code Online (Sandbox Code Playgroud)
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);
}
Run Code Online (Sandbox Code Playgroud)
<button type="button">Click me to<br />Request Dialog</button>

<dialog>
  <h2>My Dialog</h2>
</dialog>
Run Code Online (Sandbox Code Playgroud)

小智 5

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

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
}
Run Code Online (Sandbox Code Playgroud)
.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);
  }
}
Run Code Online (Sandbox Code Playgroud)
<button onclick="openModal()">open modal</button>
<dialog class="modal">
    <button onclick="closeModal()">close modal</button>
</dialog>
Run Code Online (Sandbox Code Playgroud)

  • 好的!但是,如果您按 Escape 键,模式会立即关闭,从而绕过关闭动画。您知道解决方法吗? (3认同)

G-C*_*Cyr 4

如果您使用 a 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;
 }
Run Code Online (Sandbox Code Playgroud)