gpt4 book ai didi

css - 如何在 pseudo 的 css 内容属性中获取插槽内容; :before element (or :;after) in a web component?

转载 作者:太空宇宙 更新时间:2023-11-04 05:42:45 27 4
gpt4 key购买 nike

嗯,我认为问题在标题中:在带有 shadowRoot 的 Web 组件中,我想在伪::before 或::after 元素的内容属性内使用槽文本内容。这可以让我获得更多台词。

您有想法、建议或解决方案吗?

最佳答案

您可以通过使用 CSS 自定义属性作为 ::before::aftercontent 的来源来实现这一点,并且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>

关于css - 如何在 pseudo 的 css 内容属性中获取插槽内容; :before element (or :;after) in a web component?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59023420/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com