作者:忧伤的嫖客 | 来源:互联网 | 2023-01-31 14:56
我想为用户提供一个按钮来更改整个网站的主题.我正在使用bootstrap".scss"文件.这是我做的:
我在"src/styles"文件夹中有"dark-styles.scss"和"light-styles.scss".这两个文件都覆盖了我需要覆盖的类和方法,并且还从"node-module"导入默认值的"bootstrap.scss".当我通过".angular-cli.json"向应用程序提供任何这些文件时,如下所示; 它完美地运作.
"styles": [
"../node_modules/font-awesome/css/font-awesome.css",
"../node_modules/@swimlane/ngx-datatable/release/index.css",
"../node_modules/@swimlane/ngx-datatable/release/assets/icons.css",
"../src/styles/dark-styles.scss"
],
要么,
"styles": [
"../node_modules/font-awesome/css/font-awesome.css",
"../node_modules/@swimlane/ngx-datatable/release/index.css",
"../node_modules/@swimlane/ngx-datatable/release/assets/icons.css",
"../src/styles/light-styles.scss"
],
如果我提供黑暗,主题是黑暗的,如果我提供光线,主题是光.
但我想要实现的是动态允许用户更改主题.因此,基于stackoverflow中的其他答案; 我在我的应用程序组件中访问了"文档",这也是我的根组件.它允许我访问整个html页面,其中我有一个链接标记,我可以从app-component设置.
HTML文件
content .....
角cli.json
"styles": [
"../node_modules/font-awesome/css/font-awesome.css",
"../node_modules/@swimlane/ngx-datatable/release/index.css",
"../node_modules/@swimlane/ngx-datatable/release/assets/icons.css"
],
应用程序,组件:
import { Component, OnInit, Inject } from '@angular/core';
import { DOCUMENT } from '@angular/platform-browser';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss'],
})
export class AppComponent implements OnInit {
currentTheme: string;
constructor( @Inject(DOCUMENT) private document) {
}
ngOnInit() {
this.currentTheme = 'dark';
this.document.getElementById('theme').href = '../styles/dark-styles.scss';
}
handelChangeTheme(event) {
if (this.currentTheme === 'dark') {
this.document.getElementById('theme').href = '../styles/light-styles.scss';
this.currentTheme = 'light';
console.log('light');
} else {
this.document.getElementById('theme').href = '../styles/dark-styles.scss';
this.currentTheme = 'dark';
console.log('dark');
}
}
}
在触发事件"handleChangeTheme"时,#theme的href在html文件中发生变化.但它不会更新或应用样式.我知道它与WebPack及其编译scss文件的方式有关.有没有人遇到类似的情况或知道这个问题的解决方案.谢谢
1> Volodymyr Bi..:
我刚刚在本地做了你的例子,type="text/scss"
在我改变text/css
它开始工作之后似乎是问题.我首先想到你需要重新创建元素,但问题似乎与类型有关
由于其主题,我会建议你使用这些文件的编译版本的CSS把它们放到assets
文件夹和角度,CLI将在复制它们serve
和build
另外当你在你的angular中引用scss时,用webpack编译为css.