注册新元素

定义 <initially-hidden> 自定义元素,该元素隐藏其内容,直到经过指定的秒数。

const InitiallyHiddenElement = document.registerElement('initially-hidden', class extends HTMLElement {
  createdCallback() {
    this.revealTimeoutId = null;
  }

  attachedCallback() {
    const seconds = Number(this.getAttribute('for'));
    this.style.display = 'none';
    this.revealTimeoutId = setTimeout(() => {
      this.style.display = 'block';
    }, seconds * 1000);
  }

  detachedCallback() {
    if (this.revealTimeoutId) {
      clearTimeout(this.revealTimeoutId);
      this.revealTimeoutId = null;
    }
  }
});
<initially-hidden for="2">Hello</initially-hidden>
<initially-hidden for="5">World</initially-hidden>