2013-08-24 18 views
8

我試圖設計一個自定義元素標記,並且似乎無法從元素的<style>標記中完成,或者至少我不知道要使用哪個選擇器。我試過了自定義元素的標籤名稱和template,但都不起作用。您如何在元素中設置自定義元素的標記?

<polymer-element name="my-test" constructor="MyTest"> 
    <template> 
    <style> 
     my-test { 
     border: solid 1px #888; /* doesn't work */ 
     } 
     .title { 
     color: blue; /* works */ 
     } 
    </style> 
    <div class="title">{{ title }}</div> 
    </template> 

我使用polymer.dart,所以有可能是在其執行一定的滯後性,但我想知道應該如何在polymer.js工作。

+0

這些日子裏,你不再需要polymer.dart構造屬性。至少,我不需要它。 –

回答

8

正如在另一個答案中所述,要設置陰影DOM的主機樣式,請使用@host選擇器。在自定義元素的情況下,自定義元素的主機本身。

下面是如何從自定義元素的<style>標記中對主機元素或自定義元素本身進行設置的示例。

<!DOCTYPE html> 

<html> 
<head> 
    <title>index</title> 
    <script src="packages/polymer/boot.js"></script> 
</head> 

<body> 

    <polymer-element name="my-element"> 
     <template> 
      <style> 
       @host { 
        my-element { 
        display: block; 
        border: 1px solid black; 
        } 
       } 

       p { 
        color: red; 
       } 

       #message { 
        color: pink; 
       } 

       .important { 
        color: green; 
       } 
      </style> 
      <p>Inside element, should be red</p> 

      <div id="message"> 
       The message should be pink 
      </div> 

      <div class="important"> 
       Important is green 
      </div> 

      <div> 
       <content></content> 
      </div> 
     </template> 
     <script type="application/dart" src="index.dart"></script> 
    </polymer-element> 

    <p>outside of element, should be black</p> 

    <div id="message"> 
     The outside message should be black 
    </div> 

    <div class="important"> 
     Outside important is black 
    </div> 

    <my-element>Hello from content</my-element> 

    <!-- If the script is just an empty main, it's OK to include inline. --> 
    <!-- Otherwise, put the app into a separate .dart file. --> 

    <script type="application/dart">main() {}</script> 
</body> 
</html> 

通知的@host塊樣式:

  @host { 
       my-element { 
       display: block; 
       border: 1px solid black; 
       } 
      } 

由於這種特殊的定製元素不會延伸任何元素,它不會默認爲一個塊。

這裏是它看起來風格像時:

enter image description here

+2

@host {:scope {...}}比使用選擇器的標籤名稱更通用。它也將轉變爲:主持人更自然。 http://www.polymer-project.org/articles/styling-elements.html#element-defined-styles – ebidel

+0

@ebidel不錯的提示!隨時隨地編輯我的答案:) –