TypeScript中的Shadow DOM

TypeScript中的Shadow DOM

本文解释了TypeScript中的Shadow DOM。

我们将详细讲解从 Shadow DOM 的基础知识到实际应用的全部内容,并提供实践示例代码。

YouTube Video

typescript-html-shadow-dom.html
  1<!DOCTYPE html>
  2<html lang="en">
  3<head>
  4  <meta charset="UTF-8">
  5  <title>TypeScript &amp; HTML</title>
  6  <style>
  7    * {
  8        box-sizing: border-box;
  9    }
 10
 11    body {
 12        margin: 0;
 13        padding: 1em;
 14        padding-bottom: 10em;
 15        font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
 16        background-color: #f7f9fc;
 17        color: #333;
 18        line-height: 1.6;
 19    }
 20
 21    .container {
 22        max-width: 800px;
 23        margin: 0 auto;
 24        padding: 1em;
 25        background-color: #ffffff;
 26        border: 1px solid #ccc;
 27        border-radius: 10px;
 28        box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
 29    }
 30
 31    h1, h2 {
 32        font-size: 1.2rem;
 33        color: #007bff;
 34        margin-top: 0.5em;
 35        margin-bottom: 0.5em;
 36        border-left: 5px solid #007bff;
 37        padding-left: 0.6em;
 38        background-color: #e9f2ff;
 39    }
 40
 41    button {
 42        display: block;
 43        margin: 1em auto;
 44        padding: 0.75em 1.5em;
 45        font-size: 1rem;
 46        background-color: #007bff;
 47        color: white;
 48        border: none;
 49        border-radius: 6px;
 50        cursor: pointer;
 51        transition: background-color 0.3s ease;
 52    }
 53
 54    button:hover {
 55        background-color: #0056b3;
 56    }
 57
 58    #output {
 59        margin-top: 1em;
 60        background-color: #1e1e1e;
 61        color: #0f0;
 62        padding: 1em;
 63        border-radius: 8px;
 64        min-height: 200px;
 65        font-family: Consolas, monospace;
 66        font-size: 0.95rem;
 67        overflow-y: auto;
 68        white-space: pre-wrap;
 69    }
 70
 71    .highlight {
 72        outline: 3px solid #ffc107; /* yellow border */
 73        background-color: #fff8e1;  /* soft yellow background */
 74        transition: background-color 0.3s ease, outline 0.3s ease;
 75    }
 76
 77    .active {
 78        background-color: #28a745; /* green background */
 79        color: #fff;
 80        box-shadow: 0 0 10px rgba(40, 167, 69, 0.5);
 81        transition: background-color 0.3s ease, box-shadow 0.3s ease;
 82    }
 83  </style>
 84</head>
 85<body>
 86    <div class="container">
 87        <h2>HTML Sample</h2>
 88        <div id="content"></div>
 89    </div>
 90
 91    <div class="container">
 92        <h1>JavaScript Console</h1>
 93        <button id="executeBtn">Execute</button>
 94        <div id="output"></div>
 95    </div>
 96
 97    <script>
 98        // Override console.log to display messages in the #output element
 99        (function () {
100            const originalLog = console.log;
101            console.log = function (...args) {
102                originalLog.apply(console, args);
103                const output = document.getElementById('output');
104                output.textContent += args.map(String).join(' ') + '\n';
105            };
106        })();
107
108        document.getElementById('executeBtn').addEventListener('click', () => {
109            // Prevent multiple loads
110            if (document.getElementById('externalScript')) return;
111
112            const script = document.createElement('script');
113            script.src = '/out/main.js';
114            script.id = 'externalScript';
115            //script.onload = () => console.log('typescript-html-shadow-dom.js loaded and executed.');
116            //script.onerror = () => console.log('Failed to load typescript-html-shadow-dom.js.');
117            document.body.appendChild(script);
118        });
119    </script>
120</body>
121</html>

Shadow DOM的详细解释和实用的分步指南

Shadow DOM是Web组件的关键组成部分之一。它创建了一个封闭的DOM树,将组件的样式和结构与外部隔离。在这里,我们将从Shadow DOM的基础概念到实际用例,提供详细的解释,并附上实践的示例代码。

Shadow DOM是什么?

Shadow DOM 是一种具有以下特性的网络标准技术。

  1. 封装

    Shadow DOM将组件的内部DOM结构与外部隔离。其他样式和脚本不会干扰,从而提高了可重用性。

  2. 独立的样式作用域

    Shadow DOM内部的样式不会影响外部CSS。同样地,外部样式也不会作用在Shadow DOM内。

  3. 独立的DOM树

    Shadow DOM是一个独立于常规DOM的树,父DOM对其访问受限。

Shadow DOM的基本用法

以下代码是使用 Shadow DOM 的第一个示例。

 1class MyElement extends HTMLElement {
 2  constructor() {
 3    super();
 4
 5    // Attach Shadow DOM
 6    const shadowRoot = this.attachShadow({ mode: 'open' });
 7
 8    // Add HTML and CSS inside Shadow DOM
 9    shadowRoot.innerHTML = `
10      <style>
11        p {
12          color: blue;
13          font-size: 18px;
14        }
15      </style>
16      <p>This is inside Shadow DOM!</p>
17    `;
18  }
19}
20
21// Register the custom element
22customElements.define('my-element', MyElement);
23
24document.getElementById('content').innerHTML = `
25  <my-element></my-element>
26`;
  • 浏览器将显示蓝色文字:'这是在Shadow DOM内的内容!'。此文本的样式不受外部CSS的影响。

Shadow DOM 的基本步骤

要使用 Shadow DOM,如本代码所示,需要在 JavaScript 中使用 attachShadow 方法。以下是基本步骤:。

  1. 创建自定义元素 自定义元素是一种用户定义的标签,除了标准的 HTML 标签之外,你还可以创建自己的标签。在此步骤中,你需要创建一个继承自 HTMLElement 的类,如 MyElement 类,使浏览器能够识别为新的标签。通过使用 customElements.define() 注册已创建的类,就可以在 HTML 中将其作为自定义标签使用。

  2. 附加Shadow DOM 在自定义元素内部执行 this.attachShadow(),可以创建一个 Shadow DOM

  3. Shadow DOM内添加HTML和CSSShadow DOM 内部,你可以定义自己的 HTML 结构和样式。例如,将 HTML 和 CSS 设置到 innerHTML 上,可以让其显示独立的外观和行为,不受外部 CSS 或 HTML 的影响。这样可以创建封装的组件。

Shadow DOM的模式:openclosed

Shadow DOM有两种模式:openclosed

  • 开放模式(open mode):附加到Shadow DOMshadowRoot可以从外部访问。
  • 封闭模式(closed mode):附加到Shadow DOMshadowRoot无法从外部访问。

以下是显示两种模式之间差异的代码示例。

 1class OpenElement extends HTMLElement {
 2  constructor() {
 3    super();
 4    this.attachShadow({ mode: 'open' }).innerHTML = `
 5      <p>Open Shadow DOM</p>
 6    `;
 7  }
 8}
 9
10class ClosedElement extends HTMLElement {
11  constructor() {
12    super();
13    this.attachShadow({ mode: 'closed' }).innerHTML = `
14      <p>Closed Shadow DOM</p>
15    `;
16  }
17}
18
19customElements.define('open-element', OpenElement);
20customElements.define('closed-element', ClosedElement);
21
22document.getElementById('content').innerHTML = `
23  <open-element></open-element>
24  <closed-element></closed-element>
25`;
26
27const openElement = document.querySelector('open-element') as OpenElement;
28console.log(openElement.shadowRoot); // ShadowRootが出力される
29
30const closedElement = document.querySelector('closed-element') as ClosedElement;
31console.log(closedElement.shadowRoot); // nullが出力される
  • 选择closed模式会使shadowRoot属性无法访问。

通过Shadow DOM实现样式封装

利用Shadow DOM,您可以在组件中完全封装样式。

以下示例演示了全局样式和 Shadow DOM 内部样式的分离。

 1class StyledElement extends HTMLElement {
 2  constructor() {
 3    super();
 4    const shadowRoot = this.attachShadow({ mode: 'open' });
 5
 6    shadowRoot.innerHTML = `
 7      <style>
 8        p {
 9          background-color: lightblue;
10          padding: 10px;
11          border: 1px solid blue;
12        }
13      </style>
14      <p>Shadow DOM Styled Content</p>
15    `;
16  }
17}
18
19customElements.define('styled-element', StyledElement);
20
21document.getElementById('content').innerHTML = `
22  <style>
23    p {
24      color: red;
25      font-weight: bold;
26    }
27  </style>
28
29  <styled-element></styled-element>
30`;
  • Shadow DOM 内的 p 元素不受全局样式影响,并且应用了它们自己的独特样式。

Shadow DOM的实际示例:自定义工具提示

接下来,我们介绍一个使用Shadow DOM创建自定义工具提示的示例。

 1class Tooltip extends HTMLElement {
 2  constructor() {
 3    super();
 4
 5    const shadowRoot = this.attachShadow({ mode: 'open' });
 6
 7    shadowRoot.innerHTML = `
 8      <style>
 9        :host {
10          position: relative;
11          display: inline-block;
12          cursor: pointer;
13        }
14
15        .tooltip {
16          visibility: hidden;
17          background-color: black;
18          color: white;
19          text-align: center;
20          padding: 5px;
21          border-radius: 5px;
22          position: absolute;
23          bottom: 125%;
24          left: 50%;
25          transform: translateX(-50%);
26          white-space: nowrap;
27        }
28
29        :host(:hover) .tooltip {
30          visibility: visible;
31        }
32      </style>
33      <slot></slot>
34      <div class="tooltip">Tooltip text</div>
35    `;
36  }
37}
38
39customElements.define('custom-tooltip', Tooltip);
40
41document.getElementById('content').innerHTML = `
42  <custom-tooltip>
43    Hover over me
44    <span slot="tooltip">This is a custom tooltip!</span>
45  </custom-tooltip>
46`;
  • 此代码创建了一个自定义工具提示,并在悬停时显示带样式的提示。

总结

Shadow DOM是Web组件的一项关键技术,提供了封装的DOM和样式范围。在这里,我们介绍了Shadow DOM的基础知识、使用方法、模式差异、样式封装和实际示例。利用这些方法,你可以构建可复用且健壮的组件。

您可以在我们的YouTube频道上使用Visual Studio Code跟随上述文章进行学习。 请也查看我们的YouTube频道。

YouTube Video