CSS计数器没有在阴影DOM中递增[重复]

问题描述 投票:0回答:1

这个问题在这里已有答案:

我有以下设置,其中CSS计数器适用于插槽内容,但不适用于影子DOM。

import { LitElement, css, html } from 'lit-element';

class MyElement extends LitElement {

 static get properties() {
    return {
      counter: { type: Number },
    };
  }

  render() {
    return html`
      <div><slot></slot></div>
      <div class="foo">
        <h1>Hey</h1>
        <h1>Ho</h1>
      </div>
    `;
  }
}

MyElement.styles = [
  css`
    :host {
      counter-reset: partCounter afterCounter;
    }
    :host ::slotted(*):before {
      counter-increment: partCounter;
      content: 'Slotted ' counter(partCounter) '. ';
    }
    h1:after {
      counter-increment: afterCounter;
      content: ' Shadow ' counter(afterCounter) '. ';
    }
  `,
];
customElements.define('my-element', MyElement);
<my-element>
  <h1>one</h1>
  <h1>two</h1>
</my-element>

我看到这个输出:Shadow 1 Shadow 1。预期产量:Shadow 1 Shadow 2

为什么这样做?我对解释原因更感兴趣,尽管解决方案也很好。

在Codesandbox上的工作演示:https://codesandbox.io/s/4j6n7xwmj7

P.S。:这个Github线程中的一些提示,但对我来说它表明它应该实际上正在工作:https://github.com/w3c/csswg-drafts/issues/2679

html css3 web-component custom-component shadow-dom
1个回答
2
投票

这就是你放置counter-reset的地方。

插槽内的东西需要:host,在这种情况下,我将另一个添加到.foo中。

您可以从下面的示例中看到它工作正常。

是的,我删除了所有的LIT,但无论有没有LIT,原则都是一样的。

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode:'open'}).innerHTML = `
      <style>
      :host {
        counter-reset: partCounter;
      }
      :host ::slotted(*):before {
        counter-increment: partCounter;
        content: 'Slotted ' counter(partCounter) ': ';
      }
      .foo {
        counter-reset: afterCounter;
      }
      h1:before {
        counter-increment: afterCounter;
        content: ' Shadow ' counter(afterCounter) ' - ';
      }
      </style>
      <div><slot></slot></div>
      <div class="foo">
        <h1>Hey</h1>
        <h1>Ho</h1>
      </div>
    `;
  }
}

customElements.define('my-element', MyElement);
<my-element>
  <h1>one</h1>
  <h1>two</h1>
</my-element>

为了看到每个都独立工作,我将其更改为以下内容:

class MyElement extends HTMLElement {
  constructor() {
    super();
    this.attachShadow({mode:'open'}).innerHTML = `
      <style>
      :host {
        counter-reset: partCounter -10;
      }
      :host ::slotted(*):before {
        counter-increment: partCounter;
        content: 'Slotted ' counter(partCounter) ': ';
      }
      .foo {
        counter-reset: afterCounter 30;
      }
      h1:before {
        counter-increment: afterCounter;
        content: ' Shadow ' counter(afterCounter) ' - ';
      }
      </style>
      <div><slot></slot></div>
      <div class="foo">
        <h1>Hey</h1>
        <h1>Ho</h1>
      </div>
    `;
  }
}

customElements.define('my-element', MyElement);
<my-element>
  <h1>one</h1>
  <h1>two</h1>
</my-element>
© www.soinside.com 2019 - 2024. All rights reserved.