在 Shadow DOM 中使用 :root

5
  • 我一直在研究Shadow DOM,然后遇到了一个问题。
  • 我使用:root {}语法声明一些CSS变量。但不幸的是,它没有起作用。
  • 这是我的代码
  • On 1.html

    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>Shadow DOM</title>
    </head>
    <body>
      <square-element></square-element>
      <script src="./1.js"></script>
    </body>
    
  • On 1.js:

    const htmlCode = `
    <!DOCTYPE html>
    <html lang="en">
    <head>
      <meta charset="UTF-8" />
      <meta http-equiv="X-UA-Compatible" content="IE=edge" />
      <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      <title>HTML Shadow DOM</title>
      <style>
        * {
          box-sizing: border-box;
          margin: 0;
          padding: 24px;
        }
    
        :root {
          --bg-color: cornflowerblue;
        }
    
        body {
          width: 100%;
          height: 100vh;
          background-color: antiquewhite;
        }
    
        .square {
          width: 500px;
          height: 500px;
          border: 5px solid #000;
          background-color: var(--bg-color);
        }
      </style>
    </head>
    <body>
      <div class="square"></div>
    </body>
    </html>`;
    
    customElements.define(
    "square-element",
    class extends HTMLElement {
      connectedCallback() {
        const shadow = this.attachShadow({ mode: "open" });
    
        shadow.innerHTML = htmlCode;
      }
    });
    
  • 我可以使用 :root {}Shadow DOM 中声明一些变量吗?
1个回答

7
  • shadowDOM 是一个 DocumentFragment
    与 IFRAME 不同,你不能在里面转储整个 <html> 结构

  • :root 用于 文档

  • :host 用于从 shadowRoot 内部,针对宿主元素 <square-element>

  • :host/<square-element> 本身是一个(内联块级)容器元素;
    无需添加额外的 <div> 作为 '容器' 元素

<square-element>1</square-element>
<square-element selected>2</square-element>
<square-element color="purple">3</square-element>

<style>
  :root {
    --border-color: grey;
  }
</style>

<script>
  customElements.define( "square-element", class extends HTMLElement {
      constructor() {
        super().attachShadow({mode:"open"}).innerHTML = 
        `<style>
          :host {
            --bg-color: ${this.getAttribute("color") || "teal"}; 
            display:inline-block;
            width:  100px; 
            height: 100px;
            border: 5px solid var( --border-color , red  );
            background-color: var( --bg-color     , pink );
            border-radius: var(--radius,20px);
            font:30px Arial;
            text-align:center;
            color:beige;
          }
          :host([selected]) { --bg-color: green }
          :host([color])    { --radius: 50px }
          :host(:hover)     { --border-color: gold; cursor: grab }
        </style><slot></slot>`;
      }
    });
</script>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接