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

Css 在聚合物元素中动态注入共享样式(聚合物1.2.3),css,polymer,polymer-1.0,Css,Polymer,Polymer 1.0,我有几个自己创建的嵌套聚合物元素。目前,通过使用聚合物共享样式,我能够将自定义样式注入其他元素。不幸的是,这种方法仅限于静态使用。因此,在实现时,我确实需要通过使用和导入共享样式模块来知道哪个元素应该使用哪个共享样式 但在我的用例中,我确实需要在运行时将共享样式注入聚合元素。有没有可能做到这一点 更新 我尝试了以下方法,灵感来源于甘特斯的回答: Polymer({ is : 'html-grid-row', /** * Inject style into element

我有几个自己创建的嵌套聚合物元素。目前,通过使用聚合物共享样式,我能够将自定义样式注入其他元素。不幸的是,这种方法仅限于静态使用。因此,在实现时,我确实需要通过使用
导入共享样式模块来知道哪个元素应该使用哪个共享样式

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

更新

我尝试了以下方法,灵感来源于甘特斯的回答:

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;}')
动态添加样式时,样式模块被注入元素中,但不会显示,因为polymer似乎编辑自定义样式文本内容,如下所示:

<style is="custom-style" class="style-scope html-grid-row">
    div:not([style-scope]):not(.style-scope) {font-weight: bold;}
</style>
<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> 
动态导入和引用共享样式后,聚合物包括以下内容:

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

div:not([样式范围]):not(.style范围){
字体大小:粗体;
}
解决方案


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

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

var myDomModule = document.createElement('style', 'custom-style');
myDomModule.setAttribute('include', 'mySharedStyleModuleName');
Polymer.dom(sliderElem.root).appendChild(myDomModule);
样式模块“mySharedStyleModuleName”需要导入到某个地方(如index.html)


另请参见我在使用这种方法时遇到的问题以及更多详细信息

谢谢Günther。听起来是个好办法。我明天会试试并提供反馈。我想你不能只设置
textContent
使用
custom style
include
属性。我自己不使用JS(只使用Dart),因此很难创建正确的JS翻译。我没有深入研究CSS垫片的工作原理。这种重写会导致什么问题?对于聚合元素的模板标记内的每个DOM节点,添加了一个css类
样式范围[元素名称]
ist。因此,polymer在我动态添加的CSS样式中添加的
:not([style scope])
:not(.style scope)
伪类导致这些样式不应用于模板标记中此Poylmer元素包含的HTML。听起来很奇怪。我没有这样的问题。这与使用
标记投影的元素无关?您可以尝试使用
:host div{
作为选择器。不知道polymer为什么会有这种行为。但目前我确实有一个适合我需要的解决方案(请参阅上面的解决方案)。不过,我将支持您关于Polymers GitHub项目动态样式的功能请求:-)