繁体   English   中英

如何更改 CSS:JavaScript 中的根颜色变量

[英]How to change CSS :root color variables in JavaScript

好的,我正在为我的网页创建一个允许用户更改主题的系统。 我想如何做到这一点是通过将所有 colors 作为变量,并将 colors 设置在 CSS 的根部分中。

我想做的是通过 JavaScript 更改那些 colors。 我查找了如何做到这一点,但我尝试过的任何事情都没有真正正常工作。 这是我当前的代码:

CSS:

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

JS:

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

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 时运行的代码)

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'));
  }
}

它显示警报,但实际上并没有改变任何东西。 有人可以指出我正确的方向吗?

谢谢@pvg 提供链接。 我不得不盯着它看了一会儿才明白发生了什么,但我终于想通了。

我正在寻找的神奇线是这样的:

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

这正是我想要它做的,非常感谢!

对于那些想要修改实际样式表的人,以下工作:

var sheet = document.styleSheets[0];
sheet.insertRule(":root{--blue:#4444FF}");

更多信息请访问: https : //developer.mozilla.org/en-US/docs/Web/API/CSSStyleSheet/addRule

在 JavaScript 中使用自定义属性的值,就像标准属性一样。

// get variable from inline style
element.style.getPropertyValue("--my-variable");

// get variable from wherever
getComputedStyle(element).getPropertyValue("--my-variable");

// set variable on inline style
element.style.setProperty("--my-variable", 4);

我认为这更干净,更容易记住。 设置/获取 css 变量到/从:root

const root = document.querySelector(':root');

// set css variable
root.style.setProperty('--my-color', 'blue');

// to get css variable from :root
const color = getComputedStyle(root).getPropertyValue('--my-color'); // blue

示例:一次设置多个变量

const setVariables = vars => Object.entries(vars).forEach(v => root.style.setProperty(v[0], v[1]));
const myVariables = {
  '--color-primary-50': '#eff6ff',
  '--color-primary-100': '#dbeafe',
  '--color-primary-200': '#bfdbfe',
  '--color-primary-300': '#93c5fd',
  '--color-primary-400': '#60a5fa',
  '--color-primary-500': '#3b82f6',
  '--color-primary-600': '#2563eb',
  '--color-primary-700': '#1d4ed8',
  '--color-primary-800': '#1e40af',
  '--color-primary-900': '#1e3a8a',
};
setVariables(myVariables);

旧的 jquery 魔术仍然有效

$('#yourStyleTagId').html(':root {' +
    '--your-var: #COLOR;' +
'}');

我来这里是为了寻找如何使用 JavaScript 切换:root 颜色方案,它将浏览器设置为暗模式(包括滚动条),如下所示:

:root {
    color-scheme: dark;
}

使用上面的@Daedalus 答案,这就是我根据用户偏好实现暗模式检测的方式:

    const userPrefersDarkMode = window.matchMedia('(prefers-color-scheme: dark)').matches;
    const preferredTheme = userPrefersDarkMode ? 'dark' : 'light';
    document.documentElement.style.setProperty("color-scheme", preferredTheme);

或使用保存的切换:

    const savedTheme = localStorage.getItem('theme');
    if (savedTheme == 'dark') {
        thisTheme = 'light'
    }
    else {
        thisTheme = 'dark'; // the default when never saved is dark
    }
    document.documentElement.style.setProperty("color-scheme", thisTheme);
    localStorage.setItem('theme', thisTheme);

另请参阅标题中的可选元标记

<meta name="color-scheme" content="dark light">

只读,检索数组中的所有 CSS --root规则,而不使用.getComputedStyle()

这可能允许在完整的 DOM 内容加载之前检索值,以创建使用全局根主题变量的模块,但不能通过 CSS。 (画布上下文...)

 /* Retrieve all --root CSS variables * rules into an array * Without using getComputedStyle (read string only) * On this example only the first style-sheet * of the document is parsed */ console.log( [...document.styleSheets[0].rules].map(a => a.cssText.split(" ")[0] === ":root"? a.cssText.split("{")[1].split("}")[0].split("--"): null).filter(a => a.== null)[0].map(a => "--"+a) .slice(1) )
 :root { --gold: hsl(48,100%,50%); --gold-lighter: hsl(48,22%,30%); --gold-darker: hsl(45,100%,47%); --silver: hsl(210,6%,72%); --silver-lighter: hsl(0,0%,26%); --silver-darker: hsl(210,3%,61%); --bronze: hsl(28,38%,67%); --bronze-lighter: hsl(28,13%,27%); --bronze-darker: hsl(28,31%,52%); }

TL;博士

该问题的解决方案可能是以下代码:

const headTag = document.getElementsByTagName('head')[0];
const styleTag = document.createElement("style");

styleTag.innerHTML = `
:root {
    --main-color: #317EEB;
    --hover-color: #2764BA;
    --body-color: #E0E0E0;
    --box-color: white;
}
`;
headTag.appendChild(styleTag);

解释:

尽管@Daedalus 对document.documentElement的回答做得很好,但更好的方法是将样式添加到<style> HTML 标记中(建议的解决方案)。

如果添加document.documentElement.style则所有 CSS 变量都将添加到html标记中,并且它们不会隐藏:

内联到 html 的 CSS 样式

另一方面,使用建议的代码:

const headTag = document.getElementsByTagName('head')[0];
const styleTag = document.createElement("style");

styleTag.innerHTML = `
:root {
    --main-color: #317EEB;
    --hover-color: #2764BA;
    --body-color: #E0E0E0;
    --box-color: white;
}
`;
headTag.appendChild(styleTag);

HTML 标签会更干净,如果您检查 HTML 标签,您还可以看到:root样式。

没有样式的 HTML 标签

/*My style*/
:root {
    --hl-color-green: green;
}

/*My update*/
* {
 --hl-color-green: #0cc120;
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM