在运行时更改 Polymer 应用程序的主题
Change the theme of a Polymer app at runtime
我创建了一个带有中央样式表模块的演示 Polymer-2 应用程序。在演示期间出现了关于样式是否可以针对特定用户的问题,这意味着每个用户都可以 f.e。 select 在他的选项中她想要深色还是浅色主题。
有什么办法可以实现吗?
举个例子:
当前版本的 Microsoft .NET Core 在线文档在右侧有一个组合框 "Theme",您可以在 dark/light 之间进行选择:
https://docs.microsoft.com/en-us/dotnet/api/system.io.file.copy?view=netcore-1.1#System_IO_File_Copy_System_String_System_String_
更新
daKmoR 指向的 SO 回答了我的大部分问题,但我不能接受它作为完全重复,因为在我的应用程序中,一个重要的特性是用户可以随时更改主题,而不仅仅是在初始化时.因此,我会自己回答,因为我现在已经扩展了 .
中给出的解决方案
假设主题由 CSS 个变量定义组成,那么主题文件将如下所示:
<custom-style>
<style>
html {
--background-color: blue;
--text-color: red;
}
</style>
</custom-style>
现在在其中一个应用程序组件(按钮、组合框等)中提供一些 UI 控件,用户将能够在运行时使用此辅助方法(ES6 class 语法)更改主题):
loadTheme(url) {
//Remove the currently active theme
let href = this.resolveUrl(this.currentUrl);
let link = (document.head.querySelector('link[href="' + href + '"][import-href]'));
if (link)
link.parentNode.removeChild(link);
//Import the new one
this.currentUrl = url;
Polymer.importHref(this.resolveUrl(url));
}
Polymer.importHref
将 <link>
语句添加到主文件的头部。这个 link 必须在选择另一个主题时交换。
当前活动主题的 url 保存在 currentUrl
中,这允许删除活动主题并将其替换为新主题。
我创建了一个带有中央样式表模块的演示 Polymer-2 应用程序。在演示期间出现了关于样式是否可以针对特定用户的问题,这意味着每个用户都可以 f.e。 select 在他的选项中她想要深色还是浅色主题。
有什么办法可以实现吗?
举个例子: 当前版本的 Microsoft .NET Core 在线文档在右侧有一个组合框 "Theme",您可以在 dark/light 之间进行选择: https://docs.microsoft.com/en-us/dotnet/api/system.io.file.copy?view=netcore-1.1#System_IO_File_Copy_System_String_System_String_
更新
daKmoR 指向的 SO 回答了我的大部分问题,但我不能接受它作为完全重复,因为在我的应用程序中,一个重要的特性是用户可以随时更改主题,而不仅仅是在初始化时.因此,我会自己回答,因为我现在已经扩展了
假设主题由 CSS 个变量定义组成,那么主题文件将如下所示:
<custom-style>
<style>
html {
--background-color: blue;
--text-color: red;
}
</style>
</custom-style>
现在在其中一个应用程序组件(按钮、组合框等)中提供一些 UI 控件,用户将能够在运行时使用此辅助方法(ES6 class 语法)更改主题):
loadTheme(url) {
//Remove the currently active theme
let href = this.resolveUrl(this.currentUrl);
let link = (document.head.querySelector('link[href="' + href + '"][import-href]'));
if (link)
link.parentNode.removeChild(link);
//Import the new one
this.currentUrl = url;
Polymer.importHref(this.resolveUrl(url));
}
Polymer.importHref
将 <link>
语句添加到主文件的头部。这个 link 必须在选择另一个主题时交换。
当前活动主题的 url 保存在 currentUrl
中,这允许删除活动主题并将其替换为新主题。