主要用到的方法
document.body.setAttribute(“data-theme”, ‘dark’);
window.matchMedia(‘(prefers-color-scheme: dark)’).matches
a.在全局组件中的配置
这里可以判断当前设备的主题色是什么,根据设备去实时刷新,主要用到的方法就是prefers-color-scheme,在js中可以写
if(window.matchMedia('(prefers-color-scheme: dark)').matches) {
this.dark = true
this.$store.commit('SET_THEME','dark')
Cookie.set('theme','dark',{expires:this.utilTime})
}else {
this.dark = false
this.$store.commit('SET_THEME','light')
Cookie.set('theme','light',{expires:this.utilTime})
}
}
放入仓库是用来判断刚进入时就变换主题色,尽量不让加载完成后再过度,体验不好;
放入cookie是用来记录选择过主题后以后就不再重新选择,使用上次选择的主题色,超时时间设置9999年
this.utilTime = new Date('Fri, 31 Dec 9999 23:59:59 GMT')
css中直接使用也可以
@media (prefers-color-scheme: dark){}
1. 实时监听代码
onThemeListen(){
if(window.matchMedia) {
window.matchMedia('(prefers-color-scheme: dark)').addEventListener('change', e => {
let status = e.matches ? true : false;
if (status) {
this.dark = true
Cookie.set('theme','dark',{expires:this.utilTime})
this.$store.commit('SET_THEME','dark')
document.body.setAttribute("data-theme", 'dark');
}else {
this.dark = false
Cookie.set('theme','light',{expires:this.utilTime})
this.$store.commit('SET_THEME','light')
document.body.setAttribute("data-theme", 'light');
}
});
}
},
2.点击切换主题代码
onDark(e) {
if(Cookie.get('theme') == 'dark') {
this.dark = false
Cookie.set('theme','light',{expires:this.utilTime})
this.$store.commit('SET_THEME','light')
document.body.setAttribute("data-theme", 'light');
}else {
this.dark = true
Cookie.set('theme','dark',{expires:this.utilTime})
this.$store.commit('SET_THEME','dark')
document.body.setAttribute("data-theme", 'dark');
}
},
3.进入页面后根据cookie判断代码
(首次进入我的需求是默认设置黑夜,也可根据系统主题设置,即调用a中的onThemeDark()方法)
let temp = Cookie.get('theme')
if(temp) {
if(temp == 'dark') {
this.dark = true
this.$store.commit('SET_THEME','dark')
document.body.setAttribute("data-theme", 'dark');
this.$forceUpdate()
}else {
this.dark = false
this.$store.commit('SET_THEME','light')
document.body.setAttribute("data-theme", 'light');
this.$forceUpdate()
}
}else {
// 首次进入根据是否是黑夜设置
this.dark = true
this.$store.commit('SET_THEME','dark')
Cookie.set('theme','dark',{expires:this.utilTime})
document.body.setAttribute("data-theme", 'dark');
this.$forceUpdate()
// this.onThemeDark()
}
b.nuxt项目middleware和layouts配置
1.中间件中进行cookie设置到仓库中
import getCookie from '../plugins/cookie.js'
export default function({store,req,app}){
let isServer = process.server;
if(req) {
if(isServer) {
store.state.theme = getCookie.getcookiesInServer(req).theme
}
}
}
2.布局文件中设置class类名
<template>
<div :class="$store.state.theme" >
<Nuxt/>
</div>
</template>
3.加上在全局组件中设置的document.body.setAttribute(“data-theme”, ‘dark’);
body中也存在了dark属性
body[data-theme='dark'] {backgound-color: #000;}
c.黑夜的scss文件
类名有了,data-theme有了,css就好写了…
其他
插写一条scss循环写法
@for $i from 1 through 10 {
.text-ellipsis#{$i} {
text-overflow: -o-ellipsis-lastline;
overflow: hidden;
text-overflow: ellipsis;
display: -webkit-Box;
-webkit-line-clamp: $i;
line-clamp: $i;
-webkit-Box-orient: vertical;
}
}