使用jquery或javascript更改CSS根变量 [英] Change CSS root variable with jquery or javascript

查看:68
本文介绍了使用jquery或javascript更改CSS根变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在网页中使用CSS变量并制作了某种主题颜色,

I am using CSS variables in my webpage and making a sort of theme color,

:root {
    --themeColor: #0afec0;
    --hoverColor: #fff;
    --bodyColor:  #EEF1EF;
}

现在我在任何地方都使用过var(--themeColor),我想在每次重新加载时为--themeColor分配一个随机的颜色.这可能吗?

Now i've used var(--themeColor) everywhere and i want to assign a random color to --themeColor at every reload. Is this possible?

推荐答案

您可以使用以下类似的方法轻松完成此任务:

You can do this pretty easy with something like:

document.documentElement.style.setProperty('--themeColor', 'red');

更新: 不知道问题是否只是我想的那样改变颜色.现在,我还添加了一个getRandomColor()示例.仅仅获取随机的东西可能是很大的工作量,具体取决于您是否要保存用户最后使用的颜色……

Update: Not sure if the question was just about changing the color as I thought. Now I've also added a getRandomColor() example. Just to get random stuff can be a big load of work depending if you want to save the last used color by the user or so ...

// array with colors
var colors = [
  "red",
  "green",
  "lime",
  "purple",
  "blue"
];

// get random color from array
function getColor() {
   return colors[
     Math.floor(Math.random() * colors.length)
   ];
}

// Set the color from array
document.documentElement.style.setProperty('--themeColor', getColor());

:root {
    --themeColor: orange;
}

a {
  color: var(--themeColor)
}
      
div {
  width: 100px;
  height: 100px;
  background-color: var(--themeColor);
}

<a href="#">Hello world</a>
<div>Test</div>

这篇关于使用jquery或javascript更改CSS根变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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