2017-08-28 24 views
0

雖然這可能看起來是一個重複的問題,以前要求的基於聚合物,而不是本地的CustomElements,這是關於CSS本身,沒有穿透ShadowDOM或自定義CSS屬性/變量CustomElements V1和ShadowDOM的外部樣式

所以在這裏我們有一個簡單的自定義元素(注:爲寫在新版Chrome這隻作品)

class StyleMe extends HTMLElement { 
 
\t constructor() { 
 
\t \t super(); 
 
\t \t let shadow = this.attachShadow({ mode: 'closed' }); 
 
\t \t shadow.appendChild(document.querySelector('#style-me').content.cloneNode(true)); 
 
\t } 
 
} 
 
customElements.define('style-me', StyleMe);
h1 { 
 
\t /* even !important doesn't penetrate */ 
 
\t color: red !important; 
 
}
<h1>I'm a normal heading</h1> 
 
<style-me>I'm heading hidden in style-me's shadow</style-me> 
 
<template id="style-me"> 
 
\t <style> 
 
\t \t :host { 
 
\t \t \t background: blue; 
 
\t \t \t display: block; 
 
\t \t } 
 
\t \t h1 { 
 
\t \t \t color: yellow; 
 
\t \t } 
 
\t </style> 
 
\t <h1><slot></slot></h1> 
 
</template>

這很好地演示如何使用ShadowDOM時的風格是如何隔離。

如果將<template>中的<style>的內容存儲在外部文件中,可能由預處理器(例如less)生成,那麼該做什麼最好。

後僅一番搜索找到相關的高分子我已經得出一個空白的答案,有什麼想法?


我不是在尋找自定義屬性,他們會允許我使用

<style> 
    :host { 
     background: blue; 
     display: block; 
    } 
    h1 { 
     color: var(--something); 
    } 
</style> 

並設置使用

style-me { 
    --something: yellow; 
} 

我的問題的顏色是有關移動

:host { 
    background: blue; 
    display: block; 
} 
h1 { 
    color: yellow; 
} 

在之外標籤併到一個單獨的文件

+1

相同的答案爲聚合物,用[CSS變量(https://developer.mozilla.org/en-US/docs/Web/CSS/Using_CSS_variables)。它們是規範的一部分,至少有3個瀏覽器。它們不是聚合物所特有的。 –

+0

的可能的複製[如何使用樣式風格外聚合物定製元素的內部元素?](https://stackoverflow.com/questions/42756301/how-to-style-inner-elements-of-custom-polymer-element-使用-外部樣式) –

+0

CSS屬性真的不是我要做的,以及如提到的我不使用聚合物 – AlexB

回答

1

您可以使用CSS @import url指令。

<template id="style-me"> 
    <style> 
     @import url('/css/style.css') 
    </script> 
    <h1><slot></slot></h1> 
</template> 

問題是discussed here

+0

謝謝,這就是我一直在尋找的 – AlexB