1. 把 css 文件放到服务器上,通过 XMLHttpRequest 请求文件,获取到文件内容之后替换颜色。
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    getFile(url: string) {
    return new Promise((resolve, reject) => {
    const client = new XMLHttpRequest();
    client.open("GET", url);
    client.responseType = "text";
    client.onreadystatechange = () => {
    if (client.readyState !== 4) {
    return;
    }
    if (client.status === 200) {
    const urlArr = client.responseURL.split("/");
    resolve({
    data: client.response,
    url: urlArr[urlArr.length - 1],
    });
    } else {
    reject(new Error(client.statusText));
    }
    };
    client.send();
    });
    }

    getIndexStyle() {
    this.getFile("//doc.mamaezhan.com/web/my_theme.css")
    .then(({data}: any) => {
    this.originalStyle = this.getStyleTemplate(data);
    this.writeNewStyle();
    });
    }
  2. 通过 getStyleTemplate 方法,把要更改的颜色替换成临时变量字段,如”#001528”颜色先替换成”primary”字段
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11

    getStyleTemplate(data: any) {
    const colorMap: any = {
    "#001528": "primary",
    };
    Object.keys(colorMap).forEach((key) => {
    const value = colorMap[key];
    data = data.replace(new RegExp(key, "ig"), value);
    });
    return data;
    }
  3. 再定义一个颜色变量,为需要替换的新颜色。把替换的变量字段最终替换成新的颜色
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    const colors: any = {
    primary: "#001528",
    };

    writeNewStyle() {
    let cssText = this.originalStyle;
    Object.keys(this.colors).forEach((key) => {
    cssText = cssText.replace(new RegExp("(:|\\s+)" + key, "g"), "$1" + this.colors[key]);
    });

    if (this.originalStylesheetCount === document.styleSheets.length) {
    const style = document.createElement("style");
    style.innerText = cssText;
    document.head.appendChild(style);
    } else {
    const lastChild: any = document.head.lastChild;
    lastChild.innerText = cssText;
    }
    }