Web 组件 #shadow-root css 泄漏到文档

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

我对Web组件的理解是,你可以用它来防止CSS从Web组件泄漏到父组件。我正是需要这个,但由于某种原因,Web 组件内部的样式会影响整个文档。

我当前的配对好友(ChatGPT)也不明白发生了什么😅。

    <template id="test-shadow-dom-template">
        <slot name="menu-bar"></slot>
        <span id="contents">
            <slot>The content</slot>
        </span>
    </template>
   <script type="text/javascript">
        if(!customElements.get('test-shadow-dom')) {
            customElements.define('test-shadow-dom', class extends HTMLElement {
                constructor() {
                    super();

                    let template = document.getElementById("test-shadow-dom-template");
                    let templateContent = template.content;

                    const shadowRoot = this.attachShadow({mode: 'open'});
                    shadowRoot.appendChild(templateContent.cloneNode(true));
                }
            });
        }
    </script>
<div id="test-shadow-dom-container" class="box" style="height: 100%">
    <test-shadow-dom id="my-id">
        <style>
            * {
                font-style: italic;
            }
        </style>
        <h1>Here is the actual contents...</h1>
    </test-shadow-dom>
</div>

Chrome 开发者工具

我的理解是只有

test-shadow-dom
的内容会是斜体,但网页上的所有内容都是italic

知道发生了什么事吗?

html css web-component shadow-dom
2个回答
0
投票

您应该在模板内添加样式,而不是组件。

 <template id="test-shadow-dom-template">
   <style>
     * {
       font-style: italic;
     }
   </style>
   <slot name="menu-bar"></slot>
   <span id="contents">
   <slot>The content</slot>
 </span>

或者,你可以在 javascript 中设置 css:

const style = document.createElement("style");
style.textContent = "* {font-style: italic}";
shadow.appendChild(style);

示例:https://jsfiddle.net/k8fxtacw/


0
投票

请参阅 我对 ::slotted 的详细解释

开槽内容保留在 lightDOM 中,它移动到 ShadowDOM

<slot>

因此,您的

<style>
设置全局文档的样式,就像放置在
<div>

中一样

另请注意可继承(全局)样式(请参阅长::slotted帖子)DO样式shadowDOM。

font-style
是一种可继承的风格。

您可以将

<style>
放在
<template>
内;为了简洁起见,我省略了它。

<div>This is my-element:</div>

<my-element>
  <style>
  * { /* in lightDOM, styles all of global DOM */
    font-style: italic; 
  }
  </style>
  Hello Web Component
</my-element>

<script>
customElements.define("my-element", class extends HTMLElement {
    constructor() {
        super()
            .attachShadow({ mode: "open" })
            .innerHTML = `<style>
                            * { /* in shadowDOM, styles only shadowDOM */
                              color:green;
                              font-weight: bold; 
                            }
                          </style>
                          <slot></slot>`;
    }
})
</script>

© www.soinside.com 2019 - 2024. All rights reserved.