百度公司可以做网站么,wordpress主题模板文件,邢台吧百度贴吧,跨境电商平台有哪些新手入门动态link标签加载不同主题css
**原理#xff1a;**提前准备好几套CSS主题样式文件#xff0c;在点击切换主题时#xff0c;创建link标签动态加载到head标签中#xff0c;或者是动态改变link标签的href属性。 缺点#xff1a; 动态加载样式文件#xff0c;如果文件过大网…动态link标签加载不同主题css
**原理**提前准备好几套CSS主题样式文件在点击切换主题时创建link标签动态加载到head标签中或者是动态改变link标签的href属性。 缺点 动态加载样式文件如果文件过大网络情况不佳的情况下可能会有加载延迟导致样式切换不流畅 维护不便
**优点**实现了按需加载提高了首屏加载时的性能且兼容性好
先创建主题css文件dark.css、light.css等html中link引入
headlink relstylesheet href./css/dark.css link relstylesheet href./css/light.css disable
/head切换主题
const themesCssSheet [document.querySelector(link[data-themelight]),document.querySelector(link[data-themedark]),
]
btn.addEventlistner(click,(){const dataTheme btn.getAttribute(data-theme)themesCssSheet.forEach(theme{t.disable theme.dataset.theme dataTheme })
})提前引入不同主题的css样式通过切换类名切换主题
定义好css样式
/* light样式主题 */
body{color: #f90;background: #fff;--text-color:black--header-bg:orange
}
/* dark样式主题 */
.dark {color: #eee;background: #333;--text-color:#fff--header-bg:blue
}点击切换主题时 js切换
document.body.classList.toggle(dark)css预编译器
$themes:(light:(textColor:blackheaderBg:orange),dark:(textColor:#fffheaderBg:blue)
)
$currentTheme:light;
mixin changeTheme(){each $key,$value in $themes{$currentTheme:$key !global;html[data-theme#{$key}] {content;}}
}function getTextColor(){$currentThemeObj: map-get($themes,$curTheme);return map-get($currentThemeObj,textColor);
}
function getHeaderBg(){$currentThemeObj: map-get($themes,$curTheme);return map-get($currentThemeObj,headerBg);
}function getThemeValue($key){$currentThemeObj: map-get($themes,$curTheme);return map-get($currentThemeObj,$key);
}
.content{width:100%;height:100%;changeTheme{textColor:getTextColor();headerBg:getHeaderBg();}
}基于CSS变量(最优方式)
原理根据html元素标签的属性切换所使用的主题变量。 缺点IE兼容性不行基本可以忽略。 优点便于维护基本无需css参与
定义两套多主体多套变量
:root{--text-color:black--header-bg:orange...
}
// 暗色主题
html[data-themedark]{--text-color:#fff--header-bg:blue...
}在main.js项目入口文件导入该变量便于组件使用组件中主题相关的直接使用变量主题切换时
type Theme dark | light
export const changeTheme (theme:Theme ){document.documentElement.dataset.theme theme
}CSS变量动态setProperty
定义变量
:root{--text-color:black--header-bg:orange...
}定义js更改属性值方法
export const setCssVar (prop: string, val: any, dom document.documentElement) {dom.style.setProperty(prop, val)
}
// 当样式改变
setCssVar(--text-color, color)总结
还有其他方式例如vue3 v-bind css变量和类名结合但是总体都大同小异。