CSS 伪类选择器 :modal 匹配或定位处于某种状态的元素,在这种状态下,它不会与外部的元素进行任何交互,直到该交互被消除。
伪类 :modal 可以选择多个元素,但只有一个元素会处于活动状态并接收输入。
:modal 伪类可以选择的元素是以下一个或多个元素:
- <dialog>可以使用 showModal API 打开的元素。
- 由 :fullscreen 伪类选择的元素,可以通过 requestFullscreen API 打开。
语法
:modal {
/* ... */
}
CSS :modal 示例
下面是一个示例伪类 :modal
<html>
<head>
<style>
::backdrop {
background-image: url(images/border.png);
}
:modal {
border: 8px inset blue;
background-color: lightpink;
box-shadow: 3px 3px 10px rgba(0 0 0 / 0.5);
}
</style>
</head>
<body>
<dialog>
<button autofocus>Close</button>
<p>The modal dialog has a beautiful backdrop!</p>
<p>And see my styling using :modal pseudo-class</p>
</dialog>
<button>Open the dialog</button>
<script>
const dialog = document.querySelector("dialog");
const showButton = document.querySelector("dialog + button");
const closeButton = document.querySelector("dialog button");
// "Show the dialog" button opens the dialog modally
showButton.addEventListener("click", () => {
dialog.showModal();
});
// "Close" button closes the dialog
closeButton.addEventListener("click", () => {
dialog.close();
});
</script>
</body>
</html>
在上面的例子中:
- 我们添加了一个按钮,用于打开带有对话框的模式。
- 我们添加了一个使用 ::backdrop 伪元素的背景。
- :modal 伪类用于设置对话框的样式。