使用 iron-media-query 将 CSS 应用于 Polymer 自定义元素

Applying CSS to Polymer custom element with iron-media-query

我正在尝试使用 Polymer API.

中的 <iron-media-query> 在我的自定义元素上实现简单的 'media-query' 行为

假设我有一个容器,顶部有一些文本,下面是主要内容.. 我的目标是编写媒体查询,以便当元素显示在大屏幕上时(我的测试刚好大于 768px),我可以对元素本地 DOM 样式进行一些简单的边距和填充修改。

我就是做不到。 我在这里完全错过了什么吗?

<link rel="import" href="../../bower_components/polymer/polymer.html"/>
<link rel="import" href="../../bower_components/iron-media-query/iron-media-query.html" />

<iron-media-query query="(max-width:768px)" query-matches="{{isMobilePhone}}"></iron-media-query>

<template is="dom-if" if="{{isMobilePhone}}">

    <style>
        #title {
            color: #000000;
            font-size: 1.8em;
        }
    </style>


</template>


<template>
    <style>
        :host {
            background-color: gray;
            flex-direction: column;
            margin: auto;
            margin-top: 40px;
            display: flex;
            width: 90%;
            flex-grow: 1;
            max-width: 1300px;
        }

        #title {
            color: #7DB8C9;
            font-size: 1.3em;
        }

        .content-wrapper {
            height: 100%;
        }
    </style>


    <p id="title">
        [[title]]
    </p>

    <div class="content-wrapper">
        <content select=".content"></content>
    </div>

</template>




<script>
    Polymer({

        is: 'content-container',
        properties: {
            title: String,
            isMobilePhone: Boolean
        },
        listeners: {
            'tap': 'spit'
        },
        spit: function() {
            console.log("BOOL: " + this.isMobilePhone);
        }

    });
</script> </dom-module>

我也尝试将整个模板(带有样式和标记)复制到 'if' 模板中,然后只修改我想要的样式,但它也不起作用。

(所有内容都在同一个文件中,即内容-container.html)

实现这一目标的最简单方法之一(which is the one used in the iron-media-query demo) is to use Polymer's annotated attribute bindings together with attribute selectors

元素模板的一个简单示例如下所示

<template>
<style>
  .content-wrapper ::content {
    color: blue;
  }

  .content-wrapper[mobile-layout] ::content {
    color: green;
  }
</style>

<iron-media-query query="(max-width:768px)" query-matches="{{isMobilePhone}}"></iron-media-query>
<div class="content-wrapper" mobile-layout$="[[isMobilePhone]]">
  <content></content>
</div>
</template>

这里有一个 fiddle 展示它的实际效果

<style> 标签在 <dom-module> 内的任何位置(甚至 dom-if)都会立即应用于元素(如本 demo 所示),因此将 <style>dom-if 中不会给你条件样式。

如果使用 <iron-media-query> 的唯一目的是添加条件 <style>,则根本不需要该元素。在 CSS:

中正常使用媒体查询即可
<style>
    ...

    #title {
        color: #7DB8C9;
        font-size: 1.3em;
    }

    @media (max-width:768px) {
        #title {
            color: #000000;
            font-size: 1.8em;
        }
    }
</style>

codepen