给定一个像这样的元素:

<polymer-element name="custom-element">
    <template>
        <style>
            #container {
                color: red;
            }
        </style>
        <div id="container" on-click="{{clickContainer}}">
            ... lots of other stuff here ...
        </div>
    </template>
    <script>
        Polymer('custom-element', {
            clickContainer: function() {

            }
        });
    </script>
</polymer-element>

我想要另一个包装第一个元素的元素:
<polymer-element name="my-custom-element" extends="custom-element">
    <!-- extra styling -->
    <script>
        Polymer('my-custom-element', {
            clickContainer: function() {
                this.super();
            }
        });
    </script>
</polymer-element>

我的问题:
  • 指定其他样式的最佳方法是什么?
  • 我可以将基本元素包装在其他标记中(例如另一个容器)吗?
  • 我可以从基本元素中选择元素吗?类似于<content select=".stuff">,但用于基础的阴影标记。
  • 最佳答案


  • 像往常一样,将模板放在子类(my-custom-element)中。
  • 在希望父类(super class)模板出现的位置包括<shadow></shadow>元素。
  • 将样式标签放入新模板。
  • 要为父类(super class)模板中的元素设置样式,请使用如下选择器:
  • :host::shadow .someclass { ... }
    请参见下面的示例。



    是的,您可以在<shadow></shadow>周围放置所需的任何标记。
    <div>
      <shadow></shadow>
    </div>
    



    不可以。您不能那样投影(这是与所有其他投影相反的方向)。

    如果您真的想从旧的影子根中挑选节点,可以通过直接从this.shadowRoot.olderShadowRoot中拉出节点来用代码完成。但这可能很棘手,因为父类(super class)可能对结构有期望。

    示例代码:
    <polymer-element name="my-custom-element" extends="custom-element">
    <template>
    
      <style>
          /* note that :host::shadow rules apply
             to all shadow-roots in this element,
             including this one */
          :host::shadow #container {
            color: blue;
          }
          :host {
            /* older shadow-roots can inherit inheritable
               styles like font-family */
            font-family: sans-serif;
          }
      </style>
      <p>
        <shadow></shadow>
      </p>
    
    </template>
    <script>
    
      Polymer('my-custom-element', {
        clickContainer: function() {
          this.super();
        }
      });
    
    </script>
    </polymer-element>
    

    提示:

    无论是否包含olderShadowRoot标记,
  • <shadow></shadow>都将存在,但是除非您这样做,否则它不会成为呈现的DOM的一部分。
  • 要防止创建olderShadowRoot(s),可以覆盖parseDeclarations(source)。 parseDeclarationsparseDeclarationfetchTemplate中的任何一个都可以被覆盖以产生各种效果。
  • 关于javascript - 处理 polymer 元素继承的最佳方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/24724642/

    10-12 13:27