为什么创建阴影根据appeshadow给我一个不同的结果?

时间:2017-06-19 19:21:49

标签: css web shadow-dom

我遇到了影子dom的问题。我ve found a tutorial that seems a bit old about shadow dom and it使用了创建阴影根。我被告知已经弃用了createhadowroot,应该用attachshadow替换。

问题我m having is that attachshadow does not produce the desired effect while using templates. It没有将我的元素内容复制到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

结果

result with createShadowRoot

使用attachShadow的结果

result with attachShadow

使用attachShadow没有正确复制内容,但s createShadowRoot that is deprecated. I don想要使用createShadowRoot对所有内容进行编码,因为它的支持将在未来的某个时间消失。发生了什么事?

1 个答案:

答案 0 :(得分:1)

使用Shadow DOM v1 attachShadow(),您现在应该在<slot>元素中使用<content>而不是<template>,以便从轻量级DOM中插入一些内容。

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

查看Hayato的difference of use between <slot> and <content>或Bidel的description of the <slot> tag