【问题标题】:Why styles don't apply to all slot elements in a custom web component?为什么样式不适用于自定义 Web 组件中的所有插槽元素?
【发布时间】:2021-09-30 01:07:36
【问题描述】:

我构建了一个自定义的无序列表 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>

【问题讨论】:

标签: javascript css web-component custom-component


【解决方案1】:

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>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-09-05
    • 2019-06-21
    • 1970-01-01
    • 1970-01-01
    • 2023-01-17
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多