前言
原理与方法
1.在app.html最外层套一个div,类似下面的写法
<div [class]="global.state['theme']">
//app.html的内容
</div>
这样就可以通过数据绑定更改div的class,进而影响整个app的全局样式。
2.新建文件app.global.ts,用于引入global变量,你可以将它理解成一个简单的服务。
import { Injectable } from '@angular/core';
@Injectable()
export class AppState {
//用于存储主题
state = {};
set(prop: string, value: any) {
console.log(this.state);
return this.state[prop] = value;
}
}
3.服务一般是要引入app.module.ts中的,引入之。。
类似下面这样:
import { AppState } from './app.global';
...
constructor(public global: AppState)
...
4.编写css
这里需要注意几点,主题的变更一般只有4种情况:
- 改变bg-color
- 改变color
- 改变bg
- 同时改变bg-color和color
所以编写css文件的时候请分好类,将4种情况都单独放在同一类里,这样便于修改查找。下面是我写的一个夜间主题的范例:
dark.theme.scss
.theme-dark {
//同时改变bgcolor和cololr,一般是容器
ion-header,ion-content,ion-footer,ion-item,ion-label {
background-color: #222A37 !important;
color: #9EAEC8 !important;
}
.input-wrapper,.item{
background-color: #222A37 !important;
color: #9EAEC8 !important;
}
//所有bg改变
.tabbar{
background: #222A37 !important;
}
.toolbar-background{
background-color: #222A37 !important;
}
#headDiv{
background: #222A37 ;
}
//所有color改变
h1,h2,h3,h4,h5,h6,p,body,div {
color: #9EAEC8;
}
ion-list-header{
border:none;
}
span.button-inner{
color: #9EAEC8
}
.toolbar-title{
color: #9EAEC8;
}
.tab-button[aria-selected=true] .tab-button-icon{
color: #9EAEC8 !important;
}
.tab-button[aria-selected=true] {
color: #9EAEC8 !important;
}
.tab-button-icon{
color: #5b5e7f !important;
}
.tab-button{
color: gray !important;
}
//所有bg-color改变
ion-list {
background-color: #222A37;
}
.button-round{
background-color: #2f4467 !important;
}
.fab{
background-color: #2f4467 !important;
}
}
个人的建议是将这样的主题文件独立写入一个文件,然后再将之引入app.scss。这样看起来更简洁。
app.scss
@import 'dark.theme';//dark.theme.scss的路径
5.在任意界面更改主题
xx.ts
import { AppState } from './app.global';
...
constructor(public global: AppState){}
setTheme(theme){
//直接影响app.html中的class类名,进而实现改变样式
this.global.set('theme', theme);
...
xx.html
<button ion-button click)="setTheme('theme-dark')"><ion-icon name="moon"></ion-icon>夜间</button>
效果
1.jpg结语
文章都没人看啊。。。心凉了。原标题输入百度都搜不到我的文章