【问题标题】:<content> tag inside <style> tags for templates?模板的 <style> 标签内的 <content> 标签?
【发布时间】:2016-08-27 22:53:08
【问题描述】:

我正在编写 Web 组件的演示,我的标记结构如下:

<a-component>
    <the-color>red</the-color>
</a-component>

&lt;the-color&gt;&lt;template&gt; 标签中,我需要它为&lt;a-component&gt; 应用background-color: &lt;any color&gt;。这是我目前所拥有的:

<style>
      :host {
        display: inline-block;
      }
</style>

如何使它从&lt;content&gt; 变为“红色”并将其应用于background-color: red&lt;a-component&gt;?此外,我正在使用 Shadow DOM 通过运行时 Javascript 将模板插入到页面中。谢谢!

【问题讨论】:

    标签: css html web-component html5-template


    【解决方案1】:

    我不认为&lt;content&gt; 标签是从DOM 中提取字符串以设置CSS 规则的最佳方式。

    相反,您可以在自定义元素的createdCallback 方法中直接使用this.querySelector('the-color').textContent

    document.registerElement( 'a-component', { 
        prototype: Object.create( HTMLElement.prototype, {
            createdCallback: {
                value: function () 
                {
                    var root = this.createShadowRoot()
                    root.appendChild( document.importNode( template.content, true ) )
                    this.style.backgroundColor = this.querySelector( 'the-color' ).textContent
                }
            }
        } )
    } )
    

    但是如果你想通过&lt;template&gt;里面的&lt;content&gt;获取值,你可以使用getDistributedNodes方法:

    document.registerElement('a-component', {
      prototype: Object.create(HTMLElement.prototype, {
        createdCallback: {
          value: function() {
            //apply template to Shadow DOM
            var root = this.createShadowRoot()
            root.appendChild(document.importNode(template.content, true))
            
            //select the content tag, then get the inserted node
            var content = root.querySelector('content[select=the-color]')
            var nodes = content.getDistributedNodes()
            
            //apply the content of the first node to the style's property
            color = nodes[0].textContent
            this.style.backgroundColor = color
          }
        }
      })
    })
    <template id='template'>
      I'm a <content select='the-color'></content> component
    </template>
    <a-component>
      <the-color>red</the-color>
    </a-component>

    【讨论】:

    • 谢谢!我希望用 CSS 来做,但这没关系。另外,您能解释一下为什么需要使用getDistributedNodes 方法吗?
    • 因为您要访问的元素&lt;the-color&gt; 不是Shadow DOM 的一部分,所以您无法通过querySelector 选择它。为了实现它,WebComponents 提供了content.getDistributedNodes 方法。它允许访问通过&lt;content&gt; 标签插入的元素。
    • 谢谢!我真的很困惑
    猜你喜欢
    • 2013-03-09
    • 2014-07-25
    • 2014-04-03
    • 2013-11-21
    • 1970-01-01
    • 2011-10-07
    • 1970-01-01
    • 2011-06-14
    • 2013-11-24
    相关资源
    最近更新 更多