Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Web 站点动态主题切换实现 #73

Open
shanejix opened this issue Oct 16, 2021 · 0 comments
Open

Web 站点动态主题切换实现 #73

shanejix opened this issue Oct 16, 2021 · 0 comments
Labels

Comments

@shanejix
Copy link
Owner

shanejix commented Oct 16, 2021

同步链接: https://www.shanejix.com/posts/Web 站点动态主题切换实现/

最近调研 web 站点动态主题切换的实现,记录如下

hack: replacement css file

站点维护多套主题,动态替换不同主题文件

<!-- 主题样式 -->
<link href="theme.css" rel="stylesheet" type="text/css" />

<!-- 方法一:替换 href -->
<link href="another-theme.css" rel="stylesheet" type="text/css" />

<!-- 方法二:通过 alternate 属性控制 -->
<link href="theme.css" rel="stylesheet" type="text/css" />
<link href="another-theme.css" rel="stylesheet" type="text/css" alternate />

less modifyVars

在客户端加载 less 通过的 less 的 modifyVars 在浏览器中动态修改主题

  1. 在入口 index.html 引入 less.min.js
<script type="text/javascript" src="/static/less.min.js" />

<!-- or -->

<script type="text/javascript" src="//xx.cdn.less.min.js" />
  1. 在入口 index.html 引入主题色文件
<link rel="stylesheet/less" type="text/css" href="/static/theme.less" />
  1. theme.less
@primaryColor: red;

.page {
  backgroud: @primaryColor;
  color: @primaryColor;
}
  1. 动态修改主题
handleColorChange (color) {
    less.modifyVars({
        '@primaryColor':color
    })
    .then(() => {
         console.log('修改成功');
    });
};

demo:

css variable

对于现代浏览器,css 变量是一种更廉价的动态更改主题的方式(不支持 IE 11)

  1. 定义主题变量(注意全局变量定义在 根元素上)
:root {
  --primaryColor: red;
}

.page {
  backgroud: var(--primaryColor);
  color: var(--primaryColor);
}
  1. 动态更改主题
// 替换变量值
document.body.style.setProperty("--primaryColor", "blue");

// or

// 动态加载不同主题变量

小结

可以看出,上述的思想都是一致的,要么替换文件要么修改变量。巧的是,antd 在最新的版本中也支持了动态主题,其思路是直接将 less 中的变量 转化为 css variables 挂在全局。可以学习下 ant-design/ant-design#31496

references

作者:shanejix
出处:https://www.shanejix.com/posts/Web 站点动态主题切换实现/
版权:本作品采用「署名-非商业性使用-相同方式共享 4.0 国际」许可协议进行许可。
声明:转载请注明出处!

@shanejix shanejix added the CSS label Oct 16, 2021
@shanejix shanejix changed the title 动态主题切换实现 Web站点动态主题切换实现 Oct 18, 2021
@shanejix shanejix changed the title Web站点动态主题切换实现 Web 站点动态主题切换实现 Oct 20, 2021
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant