2015-11-19 59 views
0

我是聚合物新手,需要您的幫助。我想創建一個這樣的簡單元素:<my-custom-element></my-custom-element>,如果可以像這樣更改元素的背景顏色,我會更喜歡:<my-custom-element backgroudcolor="#000"></my-custom-element>如何使用可用於設置樣式的屬性創建自定義元素

我想是這樣的:

<dom-module id=「my-custom-element」> 
    <template> 
     <style>div{height:70px; width:60px;}</style> 
     <div></div> 
    </template> 
    <script> 
     Polymer({ 
      is: 「my-custom-element」, 
      properties: { 
      backgroundcolor : {` 
       type: String, 
       value: #fff, 
       notify: true 
      } 
      }, 
      created: function(){ 
      this.style.background = this.backgroundcolor; 
      } 
     }) 
    </script>` 
</dom-module> 

,但沒有鍛鍊。請我怎麼去實現這一點。謝謝

回答

2

你需要讓它知道'這個'是什麼,我猜它是div,但你可以通過class或ID來做到這一點(這種方式只會做到它的第一件事遇到該標準

匹配
Polymer.dom(this.root).querySelector("div").style.background = this.backgroundcolor 

編輯:

而且一些最佳做法會讓你的代碼是這樣的:

<dom-module id=「my-custom-element」> 
    <style> 
    #someid { 
     height:70px; 
     width:60px; 
    } 
    </style> 
    <template> 
     <div id="someid"></div> 
    </template> 
    <script> 
     Polymer({ 
      is: 「my-custom-element」, 
      properties: { 
      backgroundcolor : { 
       type: String, 
       value: #fff, 
       notify: true 
      } 
      }, 

      ready: function() 
      { 
      Polymer.dom(this.root).querySelector("#someid").style.background = this.backgroundcolor; 
      } 
     }) 
    </script>` 
</dom-module> 
+0

謝謝你,它的工作一點點微小的改變是必要的,但! ,'created'必須是chan ge到'ready'回調 – osa

+0

@osa如果你將代碼附加到'backgroundcolor'屬性的觀察者身上,那麼每次改變它的背景顏色都會更好。 –

相關問題