美文网首页
Web动态主题方案

Web动态主题方案

作者: 低调的颜某人 | 来源:发表于2020-06-11 14:54 被阅读0次

    方案一:设置网页属性

    第一步:设置html标签如下(或者通过js修改,忽略这一步)
    //dark 可以替换为自己想要的变量()
    <html theme='dark'> 
    </html
    
    第二步:在css/less/sass文件中编写如下
    :root{
    --light-body-bg-color:'#eeeeee';
    --body-bg-color:var(--light-body-bg-color);
    /* 这里面为默认主题配色*/
    }
    :root[theme='dark']{
    --dark-body-bg-color:'#2f2f2f';
    --body-bg-color:var(--dark-body-bg-color);
      /* 这里面为dark主题的配色*/
    }
    //如果有多种主题,按照上面写更多就可以
    :root[theme='atom-one-light']{}
    :root[theme='atom-one-dark']{}
    
    body{
      background-color:var(--body-bg-color)
    }
    
    第三步:通过js切换主题
    //我只有默认和暗黑,所以按照下面的写法
      if (document.documentElement.hasAttribute('theme')) {
         document.documentElement.removeAttribute('theme');
       } else {
        document.documentElement.setAttribute('theme', 'dark');
       }
    //也可以这样写
    switch(theme){
      case 'dark':
        document.documentElement.setAttribute('theme', 'dark');
        break;
      //...
      //...
      default:
        document.documentElement.removeAttribute('theme');
        break;
    }
    

    最后,如果想要重新打开时主题是最后一次修改,把theme主题放在localStorage,每次打开网页时,从localStorage获取

    方案二:编译多个css文件,动态引入css样式文件

    这个方法我不常用,请左转百度。
    个人认为第一种方式更合理,减小前端代码(虽然css文件占用不大)

    相关文章

      网友评论

          本文标题:Web动态主题方案

          本文链接:https://www.haomeiwen.com/subject/xwsbtktx.html