聚合物:轻质 DOM 与本地 DOM

Polymer : Light DOM vs Local DOM

Polymer 的 light DOM 和 local DOM 有什么区别? 来自文档 (1):

The DOM that an element creates and manages is called its local DOM. This is distinct from the element's children which are sometimes called its light DOM for clarity.

这似乎没什么帮助。光 DOM 不应该包含 children 吗?如果是的话,本地 DOM 包含什么?

[1] https://www.polymer-project.org/1.0/docs/devguide/local-dom

这里有一个例子来解释区别。假设您有以下自定义元素:

<dom-module id="x-foo">

  <template>
    <div>I am local dom</div>
    <content></content>
  </template>

  <script>
    Polymer({
      is: 'x-foo'
    });
  </script>

</dom-module>

你在文档中这样使用它:

<x-foo>I am light dom</x-foo>

你放入元素模板的内容是本地dom。当您使用它时,您作为子项放入自定义元素的内容是 light dom。所以,local dom 是由元素的创建者决定的,而 light dom 是由元素的使用者设置的。当然,当您同时创建和使用自己的自定义元素时,您可以灵活地把什么放在哪里。

如果您创建一个组件 <a-component>,那么它有自己的标记(它的模板),即本地 DOM。该模板可以包含 <content></content> 个标签(一个未命名的和多个命名的),其中 children 被投影到。添加为 children 的内容显示在灯光 DOM.

当我们有一个 <a-component> 并且它是本地 DOM

<dom-module id="a-component">
  <template>
    <div>A</div> 
    <content></content>
    <div>B</div>
  </template>
</dom-module> 

我们像这样使用它

<a-component>
  <div>C</div>
</a-component>

然后 <div>C</div> 显示在灯光 DOM 中。结果 DOM 在浏览器中看起来像

    <div>A</div> 
    <div>C</div>
    <div>B</div>

其中 <div>A</div><div>B</div> 从内部看称为局部 DOM <a-component> 从外部看称为阴暗或阴影 DOM组件和 <div>C</div> 在 DOM.

如果我们再次采用此标记,我们将添加到页面中

<a-component>
  <div>C</div>
</a-component>

你看到 <div>C</div> 是由组件的用户直接添加的,而 <div>A</div><div>B</div> 是隐藏的(在阴影中),只有在 [=14= 之后才显示出来] 由浏览器处理。

shady 和 shadow 的区别在于 Polymer 是否启用全阴影 DOM。 Shady 在某种程度上模仿阴影,但有一些显着差异,这就是它有不同名称的原因。