如何在JavaScript中更改CSS:root颜色变量 [英] How to change CSS :root color variables in JavaScript

查看:2494
本文介绍了如何在JavaScript中更改CSS:root颜色变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我正在为我的网页创建一个系统,允许用户更改主题.我想通过将所有颜色作为变量来实现此目的,并且颜色是在CSS的:root部分中设置的.

Alright, I'm creating a system for my webpage that allows users to change the theme. How I want to accomplish this is by having all the colors as variables, and the colors are set in the :root part of the CSS.

我想做的是通过JavaScript更改这些颜色.我抬头看怎么做,但是我尝试的任何事情实际上都无法正常工作.这是我当前的代码:

What I want to do is change those colors via JavaScript. I looked up how to do it, but nothing that I attempted actually worked properly. Here's my current code:

CSS:

:root {
  --main-color: #317EEB;
  --hover-color: #2764BA;
  --body-color: #E0E0E0;
  --box-color: white;
}

JS:

(用于设置主题的代码,只需单击按钮即可运行)-我没有费心将:root更改添加到其他2个主题中,因为它不适用于Dark主题

(Code to set the theme, it's ran on the click of a button) - I didn't bother adding the :root change to the other 2 themes since it doesn't work on the Dark theme

function setTheme(theme) {
  if (theme == 'Dark') {
    localStorage.setItem('panelTheme', theme);
    $('#current-theme').text(theme);
    $(':root').css('--main-color', '#000000');
  }
  if (theme == 'Blue') {
    localStorage.setItem('panelTheme',  'Blue');
    $('#current-theme').text('Blue');
    alert("Blue");
  }
  if (theme == 'Green') {
    localStorage.setItem('panelTheme', 'Green');
    $('#current-theme').text('Green');
    alert("Green");
  }
}

(加载html时运行的代码)

(Code that is ran when the html is loaded)

function loadTheme() {
  //Add this to body onload, gets the current theme. If panelTheme is empty, defaults to blue.
  if (localStorage.getItem('panelTheme') == '') {
    setTheme('Blue');
  } else {
    setTheme(localStorage.getItem('panelTheme'));
    $('#current-theme').text(localStorage.getItem('panelTheme'));
  }
}

它显示警报,但实际上未更改任何内容.有人可以指出我正确的方向吗?

It shows the alert, but does not actually change anything. Can someone point me in the right direction?

推荐答案

感谢@pvg提供链接.我不得不凝视一下以了解发生了什么,但是我终于明白了.

Thank you @pvg for providing the link. I had to stare at it for a little to understand what was going on, but I finally figured it out.

我一直在寻找的神奇线是:

The magical line I was looking for was this:

document.documentElement.style.setProperty('--your-variable', '#YOURCOLOR');

这确实符合我的要求,非常感谢!

That did exactly what I wanted it to do, thank you very much!

这篇关于如何在JavaScript中更改CSS:root颜色变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆