`document` 没有引用 shadowDom

`document` doesn't refer to the shadowDom

所以我有这样的代码:

<template id="cool-btn-template">
  <script>
    const button = document.getElementById('click-me');
    button.addEventListener('click', event => alert(event));
  </script>
  <style>
    #click-me {
      all: unset;
      background: tomato;
      border: 0;
      border-radius: 4px;
      color: white;
      font-family: Helvetica;
      font-size: 1.5rem;
      padding: .5rem 1rem;
    }
  </style>
  <button id="click-me">Log click event</button>
</template>

<cool-btn></cool-btn>

<script>
  class CoolBtn extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById('cool-btn-template');
      const shadowRoot = this.attachShadow({mode: 'open'});
      shadowRoot.appendChild(template.content.cloneNode(true));
    }
  }

  customElements.define('cool-btn', CoolBtn);
</script>

如果您 运行 代码,您会注意到模板脚本标记中的 document 指的是整个文档,而不是 shadowDom。如何让 document 表示它的 shadowDom?

我相信自定义元素的所有 JavaScript 都应该放在其 class 中,这就是您将其范围限定到元素的方式:

<template id="cool-btn-template">
  <style>
    #click-me {
      all: unset;
      background: tomato;
      border: 0;
      border-radius: 4px;
      color: white;
      font-family: Helvetica;
      font-size: 1.5rem;
      padding: .5rem 1rem;
    }
  </style>
  <button id="click-me">Log click event</button>
</template>

<cool-btn></cool-btn>

<script>
  class CoolBtn extends HTMLElement {
    constructor() {
      super();
      const template = document.getElementById('cool-btn-template');
      const shadowRoot = this.attachShadow({mode: 'open'});
      shadowRoot.appendChild(template.content.cloneNode(true));
      shadowRoot.getElementById('click-me').addEventListener('click', event => alert(event))
    }
  }

  customElements.define('cool-btn', CoolBtn);
</script>