vue element全局换色!

2个方案,可以分别实现,或者2个都用!

方案1、指定颜色,无非就是重新弄一个css,再替换下就行了!

方案2、随便选颜色随便换色!有点单一,不过也有办法可以解决!

方案1、指定颜色

这玩意你要有耐心,就自己重新写一份咯!

好吧!言归正传,看element的官网的自定义主题!

1、自己在线编辑一份然后下载也行!这方法还简单些

https://element.eleme.io/#/zh-CN/theme/preview

2、复杂点方法

1、下载几份变量文件

npm i element-theme -g //安装「主题生成工具」
# 拉取一份css
# 从 npm
npm i element-theme-chalk -D

# 从 GitHub
npm i https://github.com/ElementUI/theme-chalk -D

然后在根目录生成一个 element-variables.scss

et -i
// 如不不行 使用 node_modules/.bin/et -i

然后你在里面改那些乱七八糟的颜色变量就行了!

image.png

然后使用

et

就会在根目录下生成一个theme/css文件

2、要用到神器gulp-css-wrap

先安装,安装到本地就行了 如果别人要用 就-D吧!

npm install  gulp

//2.安装gulp-clean-css
npm install gulp-clean-css

//3.安装gulp-css-wrap
npm install gulp-css-wrap

然后根目录新建gulpfile.js文件

// gulpfile.js
var path = require('path')
var gulp = require('gulp')
var cleanCSS = require('gulp-clean-css')
var cssWrap = require('gulp-css-wrap')
gulp.task('css-wrap', function () {
    return gulp.src(path.resolve('./theme/index.css'))
    /* 找需要添加命名空间的css文件,支持正则表达式 */
        .pipe(cssWrap({
            selector: '.custom-1b1e24' /* 添加的命名空间 */
        }))
        .pipe(cleanCSS())
        .pipe(gulp.dest('tes/1b1e24')) /* 存放的目录 */
})
gulp.task('move-font', function() {
  return gulp.src(['./theme/fonts/']).pipe(gulp.dest('tes/fonts'));
});
gulp.task('default',['css-wrap','move-font']);

这个的目的是把所有的css加一个前缀custom-1b1e24,这样你就在最顶级切换的时候加个class就行了!加class方法 就不说了,自己随便写个都行!

<div :class='qiehhuan'>
// 点击事件就自己随便取写了
data(){
retrue{
 qiehuan:'custom-1b1e24'
}
}

想要多个 就重复一次多弄几个css文件就行了!

方案2、随意切换颜色

其实原来我也研究了好久,想想觉得很复杂! 直到研究完成,感觉原来如此,站在巨人的肩膀果然好生活!

说下原理,就是你默认要引入一份element的css

然后你去ajax获取这玩意链接,然后弄到全部的css,用replace替换下里面的颜色!

然后用<style></style>插入到</head>前面,然后就完事了!

理论说完了,直接上组件吧! 改天整个完整版的2个方法共有组件!

<template>
  <el-tooltip effect="dark" content="theme" placement="bottom">
    <el-color-picker
    v-model="theme"
    class="theme-picker"
    size="small"
    popper-class="theme-picker-dropdown"/>
    aaa
  </el-tooltip>
</template>

<script>

const version = require('element-ui/package.json').version // 获取版本号
const ORIGINAL_THEME = '#409EFF' // 如果要改变多个颜色,就用scss定义变量,获取变量即可
/*
 这个的原理就是获取你初始生成的css,然后替换里面的颜色数字,转成style到页面去!
 所以你用scss,定义好需要到时候切换的变量,就能一键切换了!
 当然,颜色选择器只有一个,到时候如果需要换吧的,只能定义个js 根据选择器的,然后生成别的颜色
*/
export default {
  data() {
    return {
      chalk: '', // content of theme-chalk css
      theme: ORIGINAL_THEME
    }
  },
  watch: {
    // 监听颜色变量
    theme(val, oldVal) {
      if (typeof val !== 'string') return
      console.log(val)
      const themeCluster = this.getThemeCluster(val.replace('#', '')) // 只要数字 如 #222222 只要222...
      const originalCluster = this.getThemeCluster(oldVal.replace('#', ''))
      console.log(themeCluster, originalCluster)
      const getHandler = (variable, id) => {
        return () => {
          const originalCluster = this.getThemeCluster(ORIGINAL_THEME.replace('#', ''))
          const newStyle = this.updateStyle(this[variable], originalCluster, themeCluster)

          let styleTag = document.getElementById(id)
          console.log(styleTag)
          if (!styleTag) {
            styleTag = document.createElement('style')
            styleTag.setAttribute('id', id)
            document.head.appendChild(styleTag)
          }
          styleTag.innerText = newStyle
        }
      }

      const chalkHandler = getHandler('chalk', 'chalk-style')

      if (!this.chalk) {
        const url = `https://unpkg.com/element-ui@${version}/lib/theme-chalk/index.css`
        this.getCSSString(url, chalkHandler, 'chalk')
      } else {
        chalkHandler()
      }

      const styles = [].slice.call(document.querySelectorAll('style'))
        .filter(style => {
          const text = style.innerText
          return new RegExp(oldVal, 'i').test(text) && !/Chalk Variables/.test(text)
        })
      styles.forEach(style => {
        const { innerText } = style
        if (typeof innerText !== 'string') return
        style.innerText = this.updateStyle(innerText, originalCluster, themeCluster)
      })
      this.$message({
        message: '换肤成功',
        type: 'success'
      })
    }
  },

  methods: {
    updateStyle(style, oldCluster, newCluster) {
      let newStyle = style
      oldCluster.forEach((color, index) => {
        newStyle = newStyle.replace(new RegExp(color, 'ig'), newCluster[index])
      })
      return newStyle
    },

    getCSSString(url, callback, variable) {
      const xhr = new XMLHttpRequest()
      xhr.onreadystatechange = () => {
        if (xhr.readyState === 4 && xhr.status === 200) {
          this[variable] = xhr.responseText.replace(/@font-face{[^}]+}/, '') //把引入的字体文件去掉,因为你本身引入了字体
          console.log(xhr.responseText)
          callback()
        }
      }
      xhr.open('GET', url)
      xhr.send()
    },

    getThemeCluster(theme) {
      const tintColor = (color, tint) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)

        if (tint === 0) { // when primary color is in its rgb space
          return [red, green, blue].join(',')
        } else {
          red += Math.round(tint * (255 - red))
          green += Math.round(tint * (255 - green))
          blue += Math.round(tint * (255 - blue))

          red = red.toString(16)
          green = green.toString(16)
          blue = blue.toString(16)
          return `#${red}${green}${blue}`
        }
      }

      const shadeColor = (color, shade) => {
        let red = parseInt(color.slice(0, 2), 16)
        let green = parseInt(color.slice(2, 4), 16)
        let blue = parseInt(color.slice(4, 6), 16)

        red = Math.round((1 - shade) * red)
        green = Math.round((1 - shade) * green)
        blue = Math.round((1 - shade) * blue)

        red = red.toString(16)
        green = green.toString(16)
        blue = blue.toString(16)

        return `#${red}${green}${blue}`
      }

      const clusters = [theme]
      for (let i = 0; i <= 9; i++) {
        clusters.push(tintColor(theme, Number((i / 10).toFixed(2))))
      }
      clusters.push(shadeColor(theme, 0.1))
      return clusters
    }
  }
}
</script>
<style scoped>

</style>


相关内容

发表评论

验证码:
点击我更换图片

最新评论