嗯,我认为问题在标题中:在具有shadowRoot的Web组件中,我想在伪::: before或:: after元素的content属性内使用插槽文本内容。这可以使我获得很多线条。
您有想法,提议,解决方案吗?
您可以通过使用CSS定制属性作为content
和::before
的::after
和slotchange
事件的源来实现:
<!DOCTYPE html>
<html lang="en">
<head>
<title>WC</title>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<script>
class XTest extends HTMLElement {
constructor() {
super();
// add shadow dom and insert template content
const shadowRoot = this.attachShadow({ mode: "open" });
const template = document.getElementById("x-test-template");
const templateContent = template.content;
shadowRoot.appendChild(templateContent.cloneNode(true));
}
connectedCallback() {
// get all the named slots
const slots = this.shadowRoot.querySelectorAll("slot[name]");
[...slots].forEach(slot => {
// add a listener to run when the slot changes
slot.addEventListener("slotchange", event => {
// get the slot name
const name = event.target.name;
// get the slot content
const text = event.target.assignedNodes()[0].textContent;
// update the custom property
this.style.setProperty(`--content-${name}`, `'${text}'`);
});
});
}
}
customElements.define("x-test", XTest);
</script>
</head>
<body>
<template id="x-test-template">
<style>
:host {
display: inline-block;
position: relative;
font-size: 2rem;
padding: 2rem;
}
:host::before,
:host::after {
content: "";
position: absolute;
top: 0;
font-size: 1rem;
}
:host::before {
/* set the pseudo selector content to the custom property */
content: var(--content-before, "");
left: 0;
}
:host::after {
/* set the pseudo selector content to the custom property */
content: var(--content-after, "");
right: 0;
}
slot[name] {
display: none;
}
</style>
<!-- slot for ::before -->
<slot name="before"></slot>
<!-- default slot -->
<slot></slot>
<!-- slot for ::after -->
<slot name="after"></slot>
</template>
<x-test>
<span slot="before">B</span>
<span>Hello</span>
<span slot="after">A</span>
</x-test>
</body>
</html>
@ lamplightdev
谢谢您的回答。
我正在寻找尚不存在的东西。因此,我选择了一个使用CSS var和setter的解决方案来设置它:
class extends HTMLElement {
set content(val) {
this.setAttribute('data-content',val);
}
constructor() {
...
当然是:
:host::before {
content: attr(data-content);
...
这似乎是我可以想象的更简单的解决方案。
我想建议Web的标准开发人员创建一个新的CSS函数:slot(name)witch,具有attr(...),var(...)和calc(...),可以帮助在Web组件内使用伪元素。有人可以告诉我提出这个建议的方式吗???>
我为我的英语不佳表示歉意(我是法语,nobdy很完美)。