在聚合物元素中动态注入共享样式(聚合物 1.2.3)

Dynamically inject shared styles in polymer element (polymer 1.2.3)

我确实有几个自己创建的嵌套聚合物元素。目前,通过使用聚合物共享样式,我可以将自定义样式注入其他元素。不幸的是,这种方法仅限于静态使用。所以在实现时我确实需要通过使用 <link rel="import" href="my-shared-style.html"><style include="my-shared-style"></style>.

导入共享样式模块来知道哪个元素应该使用哪种共享样式

但在我的用例中,我确实需要在运行时将共享样式注入到聚合物元素中。有没有可能实现这一目标?

更新

我尝试了以下受 Günters 回答启发的方法:

Polymer({
    is : 'html-grid-row',
    /**
    * Inject style into element
    * @param {string} style
    */
    injectStyle : function(style) {
        var customStyle = document.createElement('style', 'custom-style');
        customStyle.textContent = style;
        Polymer.dom(this.root).appendChild(customStyle);
    }
    /**
    * Additional Elements JS functionality is put here...
    *
    */
)}

当我现在尝试通过在运行时对元素实例调用 injectStyle('div {font-weight: bold;}') 来动态添加样式时,样式模块被注入到元素中但未显示,因为聚合物似乎编辑自定义样式文本内容,如下所示:

<style is="custom-style" class="style-scope html-grid-row">
    div:not([style-scope]):not(.style-scope) {font-weight: bold;}
</style>

有没有办法阻止 polymer 在样式规则中添加 :not([style-scope]):not(.style-scope) 前缀?

更新 2:

使用 include='my-shared-style' 引用全局共享样式确实具有相同的效果。

包括使用 html import:

全局静态导入的共享样式
<dom-module id="my-shared-style">
    <template>
        <style>
            div {
                font-weight: bold;
            }
        </style>
    </template>
</dom-module>

动态导入和引用共享式 Polymer 后包括以下内容:

<style is="custom-style" include="my-shared-style" class="style-scope 
 html-grid-row">
    div:not([style-scope]):not(.style-scope) {
        font-weight: bold;
    }
</style> 

解决方案

最后,我使用了一种变通方法,通过使用 document.register('scoped-style', {extends : 'style', prototype : ...}) 扩展 <style> HTML 元素,在运行时将样式动态注入到 Polymer 元素中。 injectStyle(style) 方法(见上文)现在直接创建一个 <style is="scoped-style"> 元素作为 Elements 根节点的子元素。事实上,它的灵感来自 https://github.com/thomaspark/scoper。到目前为止这对我有用。

我使用类似的方法成功地动态注入样式

var myDomModule = document.createElement('style', 'custom-style');
myDomModule.setAttribute('include', 'mySharedStyleModuleName');
Polymer.dom(sliderElem.root).appendChild(myDomModule);

样式模块 'mySharedStyleModuleName' 需要导入某处(如 index.html)。

另请参阅https://github.com/Polymer/polymer/issues/2681 about issues I run into with this approach and 了解更多详情