【问题标题】:Polymer element-defined styles not working聚合物元素定义的样式不起作用
【发布时间】:2015-03-28 00:59:31
【问题描述】:

首先,很抱歉关于这个主题的另一篇文章,但我在聚合物文档和 stackoverflow 上看不到任何对我有意义的内容。

我只想将样式附加到我的元素。

来自文档(https://www.polymer-project.org/0.5/articles/styling-elements.htmlhttps://www.polymer-project.org/0.5/docs/polymer/styling.html#including-stylesheets-in-an-element)it 应该是直截了当的。

 <polymer-element name="x-foo">
 <template>
 <style>
   x-foo div { ... }
 </style>
 ...

但它没有按预期工作。如果我们为元素定义样式,在元素内部,它不会被应用。

代码如下:

  <polymer-element name="x-button" noscript>
    <template>

      <style>
        /* not working */
        x-button {
          background-color: green;
        }

        /* not working */
        x-button .hithere{
          display: block;
          min-height: 50px;
          background-color: red;
          margin: 20px;
        }

        /* not working */
        x-button .hitheretoo{
          display: block;
          min-height: 50px;
          background-color: blue;
          margin: 20px;
        }
      </style>


      <div class="hithere"></div>

      <template>
        <div class="hitheretoo"></div>
      </template>


    </template>

  </polymer-element>

还有现场演示: http://codepen.io/anon/pen/yyZqMN

谢谢

【问题讨论】:

    标签: css polymer web-component


    【解决方案1】:

    ssorallen 很好地解释了 css 问题,还有更多。我无法让 :host 自己工作,并且根据浏览器,您需要填充 Shadow DOM 并添加 polyfill-next-selector 样式。

    此外,该元素永远不会被注册,因为您没有在自定义元素中使用Polymer() 函数(除非您选择不在代码示例中添加它)。这是我发现的 one possible solution 的代码笔。

    我仍然想弄清楚的一件事是嵌套的&lt;template&gt; 问题。我无法用::shadow/deep/ 穿透阴影边界。可能是一个错误。等我几分钟后看看。

    【讨论】:

      【解决方案2】:

      从内部设置元素样式时使用:host selector

      <style>
        :host {
          background-color: green;
        }
      
        .hithere {
          display: block;
          min-height: 50px;
          background-color: red;
          margin: 20px;
        }
      
        .hitheretoo {
          display: block;
          min-height: 50px;
          background-color: blue;
          margin: 20px;
        }
      </style>
      

      当您从自定义元素内部进行样式设置时,所有选择器都已经作用于该元素。通过选择x-button,您选择的是该元素的后代 的任何x 按钮,而不是元素本身。这也意味着您不需要在选择器前面加上标签名称来确定它们的范围; shadow DOM 提供范围。

      【讨论】:

      • 谢谢,问题是我对 polyfill-next-selector 的用途不太了解,并且“内容”名称让我感到困惑,因为它与 :: 不同内容。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多