【问题标题】:How to distribute (insert) content nodes programmatically如何以编程方式分发(插入)内容节点
【发布时间】:2014-04-10 13:49:47
【问题描述】:

有没有办法以编程方式将内容从 lightDOM 分发(插入)到 ShadowDOM?

我想将每个子节点包装成一个元素。 例如:

<my-list>
  <span>first element</span>
  <div>second element</div>
  <a>third element</a>
</my-link>

分发为

<my-list>
  <ul>
    <li>
      <span>first element</span>
    </li>
    <li>
      <div>second element</div>
    </li>
    <li>
      <a>third element</a>
    </li>
  </ul>
</my-link>

我不仅需要它以这种方式呈现,还需要委托整个 HTML 行为(绑定、事件等),因为每个分布式节点都可能包含整个应用程序。

我已尝试将 &lt;content select=":nth-child(..)"&gt; 元素附加到 attached 回调上的模板

attached: function(){
    //ensure any element upgrades have been processed
    this.async(function asyncAttached(){
        var list = this.$.container;
        this.children.array().forEach(function(child, childNo){
            var li = document.createElement("LI");
            console.log(list, li, child);
            li.innerHTML = '<content select=":nth-child('+childNo+')"></content>';
            list.appendChild(li);
        });
    });
}

但它不起作用(可能是因为内容已经分发)。

小提琴here

一般来说,我想要实现类似于http://jsbin.com/hegizi/3/edit,但没有硬编码类名,并使其适用于可变数量的子节点。

此外,似乎原生不支持:nth-childhttps://github.com/Polymer/polymer/issues/470

【问题讨论】:

    标签: javascript polymer web-component shadow-dom


    【解决方案1】:

    组合是 Shadow DOM 的设计目标。如果该规范错误得到修复,最好的方法是在&lt;template repeat&gt; 中使用&lt;content select=":nth-child(...)"&gt; 的有趣技巧。由于您(当前)不能使用:nth-child,您可以改为使用分布式节点和数据绑定来包装内容:

    <template repeat="{{node in nodes}}">
      <li>
        <html-echo html="{{node.outerHTML}}"></html-echo>
      </li>
    </template>
    <content id="c" select="*"></content>
    

    nodes 由以下内容生成:

    this.nodes = Array.prototype.slice.call(this.$.c.getDistributedNodes());
    

    我在这篇文章中使用&lt;html-echo&gt;https://stackoverflow.com/a/22208332/274673

    工作演示:http://jsbin.com/mamawugo/2/edit

    【讨论】:

    • 感谢@ebidel,渲染效果很好。但是,如果我做对了,您的示例不会像 &lt;content&gt; 那样分发内容。它只复制文本。我需要它来分发可能包含整个应用程序的节点。这是简化的情况:jsbin.com/robaw/3/edit
    • @ebidel 您能否通过以编程方式为内容节点分配唯一属性并插入基于所述属性选择的&lt;content&gt; 节点来“破解”此问题?
    • 查看 stackoverflow.com/questions/25564150/… 了解 Alxandr 建议的示例。
    【解决方案2】:

    W3C Bugzilla 上有一个相当老的问题:#18429 - [Shadow]: Specify imperative API for node distribution

    但就目前而言,规范中没有任何相关内容。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 2022-01-19
      • 2017-11-22
      相关资源
      最近更新 更多