我正在尝试使用 CSS 制作对话框组件的 ::backdrop 伪元素。我已经能够在 Edge 和 Chrome 上实现它,但 Firefox 似乎没有正确应用转换。
有谁知道 FF 是否不支持,或者我的代码是错误的?模态本身尊重不透明度过渡,它只是立即出现的 ::backdrop 伪元素。
这是我用于快速概念证明的代码:
const dialog = document.querySelector('dialog')
const openBtn = document.querySelector('#openBtn')
const closeBtn = document.querySelector('#closeBtn')
openBtn.addEventListener('click', open)
closeBtn.addEventListener('click', close)
function open() {
dialog.showModal()
dialog.classList.add('active')
}
function close() {
dialog.close()
dialog.classList.remove('active')
}
dialog {
opacity: 0;
transition: opacity cubic-bezier(0.35, 0, 0.2, 1) 2s;
}
dialog.active {
opacity: 1;
}
dialog::backdrop {
background: black;
transition: opacity cubic-bezier(0.35, 0, 0.2, 1) 2s;
opacity: 0;
}
dialog.active::backdrop {
opacity: 0.8;
}
<dialog>
<p>test nice</p>
<button id="closeBtn">close dialog</button>
</dialog>
<button id="openBtn">
open dialog
</button>
是的,我检查过 - 似乎
transition
和 animation
的 ::backdrop
在 Firefox 中都不起作用。box-shadow
设置为 dialog
:
const dialog = document.querySelector('dialog');
const openBtn = document.querySelector('#openBtn');
const closeBtn = document.querySelector('#closeBtn');
openBtn.addEventListener('click', open);
closeBtn.addEventListener('click', close);
dialog.addEventListener('keydown', event => {
if ( event.key === 'Escape' ){
event.preventDefault();
close();
}
});
function open() {
dialog.showModal();
dialog.classList.add('active');
}
function close() {
dialog.close();
dialog.classList.remove('active');
}
dialog {
opacity: 0;
transition: opacity 2s cubic-bezier(0.35, 0, 0.2, 1);
box-shadow: 0 0 0 100vmax rgba(0, 0, 0, .8);
}
dialog.active {
opacity: 1;
}
dialog::backdrop {
display: none;
}
<dialog>
<p>test nice</p>
<button id="closeBtn">close dialog</button>
</dialog>
<button id="openBtn">
open dialog
</button>
附注如果你想在关闭时有动画
dialog
:
const dialog = document.querySelector('dialog');
const openBtn = document.querySelector('#openBtn');
const closeBtn = document.querySelector('#closeBtn');
openBtn.addEventListener('click', open);
closeBtn.addEventListener('click', close);
dialog.addEventListener('keydown', event => {
if ( event.key === 'Escape' ){
event.preventDefault();
close();
}
});
function open() {
dialog.showModal();
dialog.classList.add('active');
}
function close() {
dialog.style.pointerEvents = 'none'; /* to prevent events during animation */
dialog.classList.remove('active');
setTimeout(() => {
dialog.close();
dialog.style.removeProperty('pointer-events')
}, 2000); /* 2000 - is transition-duration in ms */
}
dialog {
opacity: 0;
transition: opacity 2s cubic-bezier(0.35, 0, 0.2, 1);
box-shadow: 0 0 0 100vmax rgba(0, 0, 0, .8);
}
dialog.active {
opacity: 1;
}
dialog::backdrop {
display: none;
}
<dialog>
<p>test nice</p>
<button id="closeBtn">close dialog</button>
</dialog>
<button id="openBtn">
open dialog
</button>