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

phw*_*563 3 css polymer polymer-1.0

我确实有几个由我自己创建的嵌套聚合物元素。目前,通过使用聚合物共享样式,我可以将自定义样式注入其他元素。不幸的是,这种方法仅限于静态使用。因此,在实现时,我确实需要通过使用<link rel="import" href="my-shared-style.html">和导入共享样式模块来知道哪个Element应该使用哪种共享样式<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...
    *
    */
)}
Run Code Online (Sandbox Code Playgroud)

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

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

有没有一种方法可以防止聚合物将: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>
Run Code Online (Sandbox Code Playgroud)

在动态导入并引用共享样式的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> 
Run Code Online (Sandbox Code Playgroud)

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

Gün*_*uer 5

我成功地使用了这种方法来动态注入样式

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

样式模块“ mySharedStyleModuleName”需要导入到某个地方(例如index.html)。

另请参阅https://github.com/Polymer/polymer/issues/2681关于我使用这种方法遇到的问题以及/sf/answers/2425513611/,以了解更多信息