ionic2/3主题功能实现

前言

首先感谢yannbf github团队给我的灵感,在此之前我与你们大多数一样,一头雾水。看到他们的源码后看了半天也不知道怎么实现的,幸好他们机智的在文件夹内部写了一个README,看了之后恍然大悟,后来经过我的一些小小改进,现在放出来分享给大家。

原理与方法

1.在app.html最外层套一个div,类似下面的写法
//app.html的内容

这样就可以通过数据绑定更改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中的,引入之。然后再将之引入至app.component.ts中。

为什么这么做?做一个类比,普通页面的a.html和a.ts的关系在app目录中就相当于app.html和app.component.ts的关系。
也就是说,app.html能够获取app.component.ts中的数据,所以我们在app.component.ts也注入该服务。如果你没有注入,会报错global不存在。

类似下面这样:

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

效果

ionic2/3主题功能实现_第1张图片
1.jpg

结语

文章都没人看啊。。。心凉了。原标题输入百度都搜不到我的文章

你可能感兴趣的:(ionic2/3主题功能实现)