CSS - 伪类 :defined



CSS 伪类选择器 :defined 表示已使用 customElementRegistry.define() 方法定义的元素。这包括标准元素以及自定义元素。

语法


:defined {
	 	/* ... */
}

CSS :defined 示例

以下示例演示了 :defined 伪类的用法:


<html>
<head>
<style>
	 	/* standard element p given a background color, whereas custom element has no background-color set */
	 	p {
	 	 	 background-color: yellow;
	 	 	 font-family: 'Courier New', Courier, monospace;
	 	}

	 	sample-custom-element {
	 	 	 color: blue;
	 	}

	 	/* Both the standard and custom element is given the font-style as normal, font-weight as 700 and font-family as fantasy */
	 	:defined {
	 	 	 font-style: normal;
	 	 	 font-weight: 700;
	 	 	 font-family: fantasy;	
	 	}
</style>
</head>
<body>
	 	<h3><u>:defined example</u></h3> 	

	 	<sample-custom-element text="Custom element with font color blue and other styles as per the :defined pseudo-class"></sample-custom-element>

	 	<p>Standard p element with yellow background, and font as per the :defined pseudo-class</p>

	 	<script>
	 	 	 customElements.define(
	 	 	 	 	"sample-custom-element",
	 	 	 	 	class extends HTMLElement {
	 	 	 	 	constructor() {
	 	 	 	 	super();

	 	 	 	 	let divElem = document.createElement("div");
	 	 	 	 	divElem.textContent = this.getAttribute("text");

	 	 	 	 	let shadowRoot = this.attachShadow({ mode: "open" }).appendChild(divElem);
	 	 	 	 	}
	 	 	 	 	},
	 	 	 );
	 	</script>
</body>
</html>

在上面的例子中:

  • 标准元素 <p> 被赋予了一些样式( background-color: yellow; font-family: 'Courier New', Courier, monospace; )
  • 已声明自定义元素 (sample-custom-element) 并赋予了一些样式(颜色:蓝色;
  • 伪类 :defined 应用于定义的元素,其样式指定为 (font-style: normal; font-weight: 700; font-family: fantasy;)
  • 输出显示,元素(标准元素和自定义元素)都采用使用 :defined 伪类指定的样式。