当前位置: 首页 > Web前端 > HTML

网页自定义主题配色

时间:2023-04-02 22:34:30 HTML

前言你应该见过很多可以改变主题或主题颜色的网站。如果要替换几个内置方案,直接替换css文件即可,这里不多说;本文介绍用户自定义替换主题标题颜色的简单解决方案!一、相关知识点1.1CSSStyleSheet.insertRule()CSSStyleSheet.insertRule(rule,index);参数:rule:字符串,包括要插入的样式规则index:编号,插入位置,可选,默认:0document.styleSheets[0].insertRule('.selector{color:red}',0);1.2CSSStyleSheet.addRule()CSSStyleSheet.addRule(selector,cssText,index)参数:选择器:字符串,选择器文本规则:字符串,包括要插入的样式规则索引:编号,插入位置,可选,默认:length-1document。styleSheets[0].addRule('.selector','color:red',0);关于insertRule和addRule的区别addRule是专门为IE传递参数的方法略有不同,insertRule默认将样式规则添加到第一个css,而addRule默认将样式规则添加到最后。补充说明:addRule虽然是IE方法,但是chrome等主流方法也支持,可以放心使用;另一方面,insertRule也支持IE9及以上版本。1.3CSS3变量允许我们像Sass和Less一样创建变量;:root{--color:粉色;}div{颜色:var(--color);}.content{--red:红色;--string:'支持字符串';--中文名称:20个;background-color:var(--red);}遗憾的是目前不支持IE,但是可以通过JS判断varisSupported=window.CSS&&window.CSS.supports&&window.CSS.supports('--a',0);if(isSupported){/*supported*/}else{/*notsupported*/}更多关于css3变量:请点这里2.具体解决方案2.1通过insertRule/addRule实现函数setTheme(color){letlink=document.createElement("样式");让head=document.getElementsByTagName("head")[0];//设置主题色时移动原来的样式文件另外,样式虽然可以叠加,但是为了避免添加过多,最好清空。document.getElementById('主题')&&head.removeChild(document.getElementById('主题'));link.rel="样式表";link.type="文本/css";link.id="主题";head.appendChild(链接);让themeData={颜色:颜色,};让len=document.styleSheets.length-1;//进入本地存储localStorage.setItem('Theme',JSON.stringify(themeData));document.styleSheets[len].addRule('.T-BG',`background-color:${this.color}!important`);document.styleSheets[len].addRule('.T-FT',`color:${color}!important`);document.styleSheets[len].addRule('.T-FT-H:hover',`color:${color}!important`);document.styleSheets[len].addRule('.T-BD',`border-color:${color}!important`);document.styleSheets[len].addRule('.T-SD',`box-shadow:005px1px${color}!important`);document.styleSheets[len].addRule('.T-SD-H:hover',`box-shadow:005px1px${c颜色}!important`);document.styleSheets[len].addRule('.T-TSD-H:hover',`text-shadow:005px${color}!important`);document.styleSheets[len].addRule('.T-TSD',`text-shadow:005px${color}!important`);}2.2通过css3变量实现//这种方式简单很多,但是开发前请了解其兼容性,开发时主题颜色相关的颜色直接调用变量,就像你平时使用Sass函数setTheme(color){//设置变量,document.body.style.setProperty('--ThemeColor','red');}如果有什么更好的解决方案希望留言分享