CSS 计数器在阴影中不递增 DOM

CSS counter not incrementing in shadow DOM

我有以下设置,其中 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

一切都在你放置 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>