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),并为其指定了一些样式 (color: blue;)

  • 伪类:defined应用于已定义的元素,其样式指定为 (font-style: normal; font-weight: 700; font-family: fantasy;)

  • 输出显示标准元素和自定义元素都采用了使用:defined伪类指定的样式。

广告