Polymer:加载动态内容时重新加载样式

Polymer: Reload Styles when loading dynamic content

我使用 <style include="style-name"></style> 添加样式,通常效果很好。

但是,我有一个元素可以通过 JavaScript 动态加载和更改其内容。它会在某个时候从一些外部源加载新内容并相应地更新其内容。这些新内容没有应用 style-name 中的样式。

如何让 Polymer 重新评估样式并因此将它们应用于新内容?


我正在使用 Meteor + Synthesis,如果有区别的话。

为了保持样式范围,您应该使用 Polymer importHref() 和 dom() 函数,如下所示:

// ...
let importSource = Polymer.Base.importHref('path/to/external-source',
// Import is done, use the body of that
event => {
    // #container is my element which should have the content
    // but you can change to any element what you want
    // or use just the this.root
    Polymer.dom(this.$.container).innerHTML = importSource.import.body;
},
// Handle errors
event => console.error(event));
// ...

如果您使用 Shady DOM,这种方式聚合物将应用样式范围,在阴影 DOM 中它应该默认工作,但我没有测试,所以最好使用 Polymer为此内置函数。

Polymer.updateStyles() 仅在您像这样更改本地 DOM css 变量时才有效:this.customStyle['--my-toolbar-color'] = 'blue';