<分区>
<分区>
我有以下设置,其中 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>
关于html - CSS 计数器不会在影子 DOM 中递增,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55460772/