Polymer动态添加了未设置样式的元素

时间:2016-07-11 13:10:04

标签: polymer polymer-1.0

以下是我所拥有的元素的缩减版本:

<dom-module id="my-element">
    <template>
        <style>
            :host {
                display: inline;
            }

            .dark {
                background: black;
                color: white;
            }
        </style>

        <span id="container">
            <content></content>
        </span>
    </template>
    <script>
        Polymer({
            is: 'my-element',
            ready: function () {
                var containerEl = this.$.container;
                var containerText  = containerEl.textContent.trim();

                // create element
                var clippedSpan = document.createElement('span');
                clippedSpan.textContent = containerText;
                clippedSpan.classList.add("dark");

                // clear container
                containerEl.innerHTML = '';

                containerEl.appendChild(clippedSpan);

                // update the styles
                (this.domHost || Polymer).updateStyles();
            }
        });
    </script>
</dom-module>

通过将以下内容添加到index.html页面来使用:

<my-element>text goes here</my-element>

<script src="https://polygit.org/components/webcomponentsjs/webcomponents-lite.min.js"></script>
<link rel="import" href="https://polygit.org/components/polymer/polymer.html">
<dom-module id="my-element">
  <template>
    <style>
      :host {
        display: inline;
      }
      .dark {
        background: black;
        color: white;
      }
    </style>

    <span id="container">
    	  <content></content>
    	</span>
  </template>
  <script>
    Polymer({
      is: 'my-element',
      ready: function() {
        var containerEl = this.$.container;
        var containerText = containerEl.textContent.trim();

        // create element
        var clippedSpan = document.createElement('span');
        clippedSpan.textContent = containerText;
        clippedSpan.classList.add("dark");

        // clear container
        containerEl.innerHTML = '';

        containerEl.appendChild(clippedSpan);

        // update the styles
        (this.domHost || Polymer).updateStyles();
      }
    });
  </script>
</dom-module>

<my-element>text goes here</my-element>

Plunker here

我可以看到创建的span元素确实应用了类dark,但实际上并没有应用dark类的任何样式。这必须是因为它是作为孩子动态添加的。我尝试在updateStyles和全局this对象上调用Polymer函数无效。

如何确保正确应用样式?

使用<content>标记而不是属性的原因纯粹是为了简单起见。

1 个答案:

答案 0 :(得分:2)

DOM API

Polymer provides a custom API for manipulating DOM such that local DOM and light DOM trees are properly maintained.

Note: All DOM manipulation must use this API, as opposed to DOM API directly on nodes.

         Polymer.dom(containerEl).appendChild(clippedSpan);
相关问题