【问题标题】:Why createshadowroot is giving me a different result then attachshadow?为什么 createshadowroot 给我的结果与 attachshadow 不同?
【发布时间】:2017-06-19 19:21:48
【问题描述】:

我遇到了 shadow dom 的问题。我ve found a tutorial that seems a bit old about shadow dom and its 使用 createshadowroot。我已被告知 createshadowroot 已被弃用,应由 attachshadow 替换。

问题 im having is that attachshadow does not produce the desired effect while using templates. Its 没有将我的元素的内容复制到 html 中。

这是我正在使用的代码:

var nameTags = document.querySelectorAll('.nameTag');

for (i = 0; i < nameTags.length; ++i)
{
    //var shadow = nameTags[i].attachShadow({ mode: 'open' });
    var shadow = nameTags[i].createShadowRoot();
    var template = document.querySelector('#nameTagTemplate');

    var clone = document.importNode(template.content, true);

    console.log(shadow);
    console.log(template);
    console.log(template.content);
    console.log(clone);

    shadow.appendChild(clone);
}

createShadowRoot 的结果

attachShadow 的结果

内容没有被 attachShadow 正确复制但它s createShadowRoot that is deprecated. I dont 想用 createShadowRoot 编码所有内容,因为它的支持将在未来的某个时候消失。怎么回事?

【问题讨论】:

    标签: css web shadow-dom


    【解决方案1】:

    对于 Shadow DOM v1 attachShadow(),您现在应该在 &lt;template&gt; 元素中使用 &lt;slot&gt; 而不是 &lt;content&gt;,以便从 light DOM 中插入一些内容。

    <template>
        <slot name="first"></slot>
    </template>
    ...
    <div id=host>
        <div slot="first">Name</div>
    </div>
    

    查看 Hayato 的 difference of use between &lt;slot&gt; and &lt;content&gt; 或 Bidel 的 description of the &lt;slot&gt; tag。

    【讨论】:

      猜你喜欢
      • 2016-05-12
      • 1970-01-01
      • 2013-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多