为什么样式不适用于自定义 Web 组件中的所有插槽元素?

Why styles don't apply to all slot elements in a custom web component?

我构建了一个自定义无序列表 Web 组件。我正在尝试为每个 <li> 设置自定义项目符号,但项目符号仅适用于第一个列表项。

如何对所有列表项应用相同的样式?

const template = document.createElement('template');
template.innerHTML = `
  <style>
    ul {
      list-style-type: none;
      padding: 2.5rem 0;
      margin-block-start: 0;
      margin-block-end: 0;
    }
    ul li {
      background-image: url("https://www.nextiva.com/assets/svg/bullet.svg");
      background-position: 0 0.725rem;
      background-repeat: no-repeat;
      padding-left: 1.125rem;
      margin: 2rem 0;
      font-size: 1.25rem;
      line-height: 2rem;
    }
    ul li:first-child, ul li:last-child {
      margin: 0;
    }
  </style>
  <ul>
    <li><slot name="item"></slot></li>
  </ul>
`;

class CustomBulletList extends HTMLElement {

  constructor() {
    super();

    this.showInfo = true;
    this.attachShadow({
      mode: 'open'
    });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
}

window.customElements.define('custom-bullet-list', CustomBulletList);
<custom-bullet-list>
  <li slot="item">Lollipop</li>
  <li slot="item">Fruit Toast</li>
  <li slot="item">Cup Cake</li>
</custom-bullet-list>

ul li 更改为 ::slotted(li)

MDN 得到了与您尝试做的接近的用例示例。

片段:

const template = document.createElement('template');
template.innerHTML = `
  <style>
    ul {
      list-style-type: none;
      padding: 2.5rem 0;
      margin-block-start: 0;
      margin-block-end: 0;
    }
    
    ::slotted(li) {
      background-image: url("https://www.nextiva.com/assets/svg/bullet.svg");
      background-position: 0 0.725rem;
      background-repeat: no-repeat;
      padding-left: 1.125rem;
      margin: 2rem 0;
      font-size: 1.25rem;
      line-height: 2rem;
    }
    ul li:first-child, ul li:last-child {
      margin: 0;
    }
  </style>
  <ul>
    <li><slot name="item"></slot></li>
  </ul>
`;

class CustomBulletList extends HTMLElement {

  constructor() {
    super();

    this.showInfo = true;
    this.attachShadow({
      mode: 'open'
    });
    this.shadowRoot.appendChild(template.content.cloneNode(true));
  }
}

window.customElements.define('custom-bullet-list', CustomBulletList);
<custom-bullet-list>
  <li slot="item">Lollipop</li>
  <li slot="item">Fruit Toast</li>
  <li slot="item">Cup Cake</li>
</custom-bullet-list>