:defined - CSS: Cascading Style Sheets 编辑

The :defined CSS pseudo-class represents any element that has been defined. This includes any standard element built in to the browser, and custom elements that have been successfully defined (i.e. with the CustomElementRegistry.define() method).

/* Selects any defined element */
:defined {
  font-style: italic;
}

/* Selects any instance of a specific custom element */
simple-custom:defined {
  display: block;
}

Syntax

:defined

Examples

Hiding elements until they are defined

The following snippets are taken from our defined-pseudo-class demo (see it live also).

In this demo we define a very simple trivial custom element:

customElements.define('simple-custom',
  class extends HTMLElement {
    constructor() {
      super();

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

      let shadowRoot = this.attachShadow({mode: 'open'})
        .appendChild(divElem);
  }
})

Then insert a copy of this element into the document, along with a standard <p>:

<simple-custom text="Custom element example text"></simple-custom>

<p>Standard paragraph example text</p>

In the CSS we first include the following rules:

// Give the two elements distinctive backgrounds
p {
  background: yellow;
}

simple-custom {
  background: cyan;
}

// Both the custom and the built-in element are given italic text
:defined {
  font-style: italic;
}

Then provide the following two rules to hide any instances of our custom element that are not defined, and display instances that are defined as block level elements:

simple-custom:not(:defined) {
  display: none;
}

simple-custom:defined {
  display: block;
}

This is useful if you have a complex custom element that takes a while to load into the page — you might want to hide instances of the element until definition is complete, so that you don't end up with flashes of ugly unstyled elements on the page

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of ':defined' in that specification.
Living Standard

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:39 次

字数:4034

最后编辑:8年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文