2016-06-24 15 views
0

我試圖使用Polymer API中的<iron-media-query>在我的自定義元素上實現簡單的「媒體查詢」行爲。將CSS應用於具有鐵質媒體查詢的聚合物自定義元素

假設我有一個容器,頂部有一些文字,下面是主要內容。我的目標是編寫媒體查詢,以便當元素顯示在大屏幕上(大於768像素爲我的測試),我可以做一些簡單的邊距和元素本地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> 

我也試圖複製整個模板(使用樣式和標記)裏面的「如果」模板,只需要修改我想要的風格,但它也不管用。

(一切都是同一個文件,這是內容container.html內)

+0

有沒有使用'鐵媒體query'而不是CSS'媒體query'的造型任何具體的原因是什麼? – a1626

回答

1

之一來實現這一(which is the one used in the iron-media-query demo)最簡單的方法是用聚合物的annotated attribute bindings連同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顯示它在行動

+0

不錯!我該如何修改:host {}元素?我的意思是,沒有辦法添加'mobile-layout'屬性,因爲主機元素沒有標記。 –

+0

我認爲使用'reflectToAttribute'參數定義一個屬性並將其用作屬性選擇器應該足夠了[這是小提琴展示](https://jsfiddle.net/89y26823/1/)) – Alan

+0

出於某種原因,我不能讓它工作。你可以看看這個[小提琴](https://jsfiddle.net/m206r1bj/)嗎? –

2

<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

+0

我明白了......那麼鐵媒體查詢的目的是什麼?是否要添加特定的條件標記? –

+1

對,您可以使用它來根據媒體查詢有選擇地添加/刪除元素。 – tony19

+0

@DavidAzar我認爲你不能在元素風格中使用CSS媒體查詢 – Alan

相關問題