前言
首先感謝yannbf github團(tuán)隊(duì)給我的靈感,在此之前我與你們大多數(shù)一樣,一頭霧水??吹剿麄兊脑创a后看了半天也不知道怎么實(shí)現(xiàn)的,幸好他們機(jī)智的在文件夾內(nèi)部寫(xiě)了一個(gè)README,看了之后恍然大悟,后來(lái)經(jīng)過(guò)我的一些小小改進(jìn),現(xiàn)在放出來(lái)分享給大家。
原理與方法
1.在app.html最外層套一個(gè)div,類似下面的寫(xiě)法
<div [class]="global.state['theme']">
//app.html的內(nèi)容
</div>
這樣就可以通過(guò)數(shù)據(jù)綁定更改div的class,進(jìn)而影響整個(gè)app的全局樣式。
2.新建文件app.global.ts,用于引入global變量,你可以將它理解成一個(gè)簡(jiǎn)單的服務(wù)。
import { Injectable } from '@angular/core';
@Injectable()
export class AppState {
//用于存儲(chǔ)主題
state = {};
set(prop: string, value: any) {
console.log(this.state);
return this.state[prop] = value;
}
}
3.服務(wù)一般是要引入app.module.ts中的,引入之。然后再將之引入至app.component.ts中。
為什么這么做?做一個(gè)類比,普通頁(yè)面的a.html和a.ts的關(guān)系在app目錄中就相當(dāng)于app.html和app.component.ts的關(guān)系。
也就是說(shuō),app.html能夠獲取app.component.ts中的數(shù)據(jù),所以我們?cè)赼pp.component.ts也注入該服務(wù)。如果你沒(méi)有注入,會(huì)報(bào)錯(cuò)global不存在。
類似下面這樣:
import { AppState } from './app.global';
...
constructor(public global: AppState)
...
4.編寫(xiě)css
這里需要注意幾點(diǎn),主題的變更一般只有4種情況:
- 改變bg-color
- 改變color
- 改變bg
- 同時(shí)改變bg-color和color
所以編寫(xiě)css文件的時(shí)候請(qǐng)分好類,將4種情況都單獨(dú)放在同一類里,這樣便于修改查找。下面是我寫(xiě)的一個(gè)夜間主題的范例:
dark.theme.scss
.theme-dark {
//同時(shí)改變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;
}
}
個(gè)人的建議是將這樣的主題文件獨(dú)立寫(xiě)入一個(gè)文件,然后再將之引入app.scss。這樣看起來(lái)更簡(jiǎn)潔。
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類名,進(jìn)而實(shí)現(xiàn)改變樣式
this.global.set('theme', theme);
...
xx.html
<button ion-button click)="setTheme('theme-dark')"><ion-icon name="moon"></ion-icon>夜間</button>
效果

1.jpg
結(jié)語(yǔ)
文章都沒(méi)人看啊。。。心涼了。原標(biāo)題輸入百度都搜不到我的文章