主题色切换

这是一篇利用less来完成主题色切换的文章。javascript

theme-color-generator

首先咱们须要利用theme-color-generator这个包来抽取less文件中跟主题色相关的样式。css

虽然这个包有点大,可是咱们只是用它来生成主题色切换样式文件,并不会将其打包进文件中,因此没有关系。html

installjava

npm install theme-color-generator
复制代码

利用gulp等构建工具来执行下面配置的代码git

const path = require('path');
const { generateTheme } = require('theme-color-generator');

const options = {
  stylesDir: path.join(__dirname, './src/styles'), // 要抽取主题色的less文件所在目录
  varFile: path.join(__dirname, './src/styles/variables.less'), // 跟主题色相关的变量文件
  themeVariables: ['@theme-color'], // (可选项) 指定使用`varFile`中的哪些变量 (若是没有设置,将会使用全部变量)
  outputFilePath: path.join(__dirname, './public/color.less') // 生成抽取出主题色的文件
}

generateTheme(options).then(less => {
  console.log('Theme generated successfully');
})
.catch(error => {
  console.log('Error', error);
})
复制代码

接下来,咱们能够使用生成的color.less文件来切换主题色了github

方案1

把下面这段代码加入到你的html文件中ajax

<link rel="stylesheet/less" type="text/css" href="/color.less" />
<script>
  window.less = {
    async: false,
    env: 'production'
  };
</script>
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/less.js/2.7.2/less.min.js"></script>
复制代码

如今你能够使用下面的代码来切换主题色了npm

window.less.modifyVars({
  '@theme-color': '#0035ff'
})
复制代码

demogulp

方案2

咱们发现方案1使用的less文件有点大,那么咱们有没有什么办法达到更快的加载效果呢? 这里咱们引入另外一个包 theme-color-switchbash

const less = require('theme-color-switch');
const colorSource = require('!raw-loader!./public/color.less'); // theme-color-generator生成的主题色文件
less.render(
   colorSource,
   {
       modifyVars: {
           '@theme-color': '#0035ff' // 你想要修改的变量
       },
   },
   function(e, output) {
      if (e) {
          console.error(`Failed to update theme`);
      }
      if (output && output.css) {
          // 将返回的切换主题色后的css样式文件添加至style标签
          // 具体代码能够下载example查看
          addCSS(output.css);
      }
   }
);
复制代码

一样能够轻松切换主题色,但包的大小小了不少。 demo

相关文章
相关标签/搜索