我的想法是让不同的文件(.css 或 .html)包含特定主题的所有规则,并在运行时动态改变 Polymer 应用程序的外观。
我发现这种方法非常有用,Polymer 自己在这里用 using custom style at document level 描述了这种方法(使用 .html 文件)
Frequently you want to define custom property values at the document level, to set a theme for an entire application, for example. Because custom properties aren't built into most browsers yet, you need to use a special custom-style tag to define custom properties outside of a Polymer element. Try adding the following code inside the tag of your index.html file
基本上我们定义了一个 my-theme.html
,它定义了应用程序样式中使用的变量,如下所示:
<style is="custom-style">
/* Define a document-wide default—will not override a :host rule in icon-toggle-demo */
:root {
--icon-toggle-outline-color: red;
}
/* Override the value specified in icon-toggle-demo */
icon-toggle-demo {
--icon-toggle-pressed-color: blue;
}
/* This rule does not work! */
body {
--icon-toggle-color: purple;
}
</style>
然后我将它导入到我的 index.html 文件中。
然后我在 stackoverflow 上找到了 this动态改变样式的方法。
HTML
<link type="text/css" rel="stylesheet" media="all" href="../green.css" id="theme_css" />
JS
document.getElementById('buttonID').onclick = function () {
document.getElementById('theme_css').href = '../red.css';
};
这里的问题是该文件是一个 rel: stylesheet
并且更改其 href 会导致浏览器重新加载文件并应用更改,而在我的情况下更改 html 导入的 href 不会不会导致同样的效果。
有没有办法让它按照我的意愿工作?是否有更好的解决方案来实现我的目标?
最佳答案
当然,您必须使用自定义 CSS 属性和混入。如果您的网站样式正确,将很容易切换到不同的主题。
您可以通过以下方式更改自定义 CSS 属性值:
this.customStyle['--my-toolbar-color'] = 'blue';
每一个使用 var(--my-toolbal-color) 的 css 规则都会变成蓝色,一旦你调用了一个 ore 函数:
this.updateStyles();
这告诉 Polymer,嘿,我刚刚更新了样式,你能重新渲染 css 规则吗..
希望这对您有所帮助,这正是您要找的东西。因为我觉得你描述的太复杂了。
关于javascript - 动态更改使用 Polymer 构建的应用程序样式的最佳方法是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43273540/