繁体   English   中英

如何不呈现内容 <content> 在Shadow DOM中标记?

[英]How to not render the content in the <content> tag in Shadow DOM?

我目前正在开发一个Web组件(使用Polymer构建),以使元素的使用者将一些内容放入elements标记中,如下所示:

<my-element mode="fancy">
  <item>First item</item>
  <item>Second item</item>
  <item>Third item</item>
       <!-- ... -->
</my-element>

因此,下一步是在元素定义中使用<content> ,如下面的代码片段所示,将内容投影到我的自定义元素中:

<template>
  <content id="idToHandleIt" select="item"></content>
</template>

现在的问题是,所有item都被立即渲染。 但是我不想在这里显示它们,因为我必须过滤组件逻辑(JavaScript)逻辑中的元素以获取更多条件,而不仅仅是可以在select属性中使用的CSS-Selectors。

是否有人可以很好地解决该问题,或者是否有API可以让我抓住 分布式节点? 正如我现在所尝试的,使用getDistributedNodes()的唯一方法是执行以下操作:

this.querySelector('idToHandleIt').getDistributedNodes();

但是我总是需要<content>元素:(

如何手动添加到shadowRoot?

 <script src="http://www.polymer-project.org/webcomponents.min.js?20141211"></script> <link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html"> <polymer-element name="example-element"> <template></template> <script> Polymer({ ready: function() { var children = this.children; for (var i = 0; i < children.length; i++) { var childElement = children[i]; if (childElement.hasAttribute("banana") && childElement.getAttribute("amount") > 0) { this.shadowRoot.appendChild(childElement); // we have to negate one from the index for each append to the shadowRoot i--; } } } }); </script> </polymer-element> <example-element> <p banana amount="1">one banana</p> <p apple>one apple</p> <p banana amount="2">two banana</p> <p banana amount="3">three banana</p> <p banana amount="0">no banana</p> </example-element> 

幸运的是,您可以通过多种方式执行此操作,但是您应该避免设置<content>本身的样式,因为它只是一个插入点。

但是,如果要延迟实际插入,可以将<content> select属性设置为“无效”,如下所示:

 <script src="http://www.polymer-project.org/webcomponents.min.js?20141211"></script> <link rel="import" href="http://www.polymer-project.org/components/polymer/polymer.html"> <polymer-element name="x-item" noscript> <template> <div> <content></content> </div> </template> </polymer-element> <polymer-element name="example-element"> <template> <style> .container { opacity: 1; transition: all 1s linear; } [unresolved] { visibility: none; opacity: 0; } </style> <template if="{{counter > 0}}">They will appear after {{counter}}s.</template> <div unresolved?="{{counter > 0}}" class="container"> <content id="idToHandleIt" select="{{counter > 0? 'nope' : 'x-item'}}"></content> </div> </template> <script> Polymer({ counter: 5, ready: function() { this.countDown(); }, countDown: function() { if (this.counter <= 0) { return; } this.async(this.countDown, null, 1000); this.counter--; } }); </script> </polymer-element> <example-element> <x-item>Item 1</x-item> <x-item>Item 2</x-item> <x-item>Item 3</x-item> <x-item>Item 4</x-item> <x-item>Item 5</x-item> </example-element> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM