js获取/设置css变量

-

复制代码
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
<style>
  :root{
    --color: red
  }
  .a{
    color: var(--color)
  }
</style>
</head>
<body>
  <div class="a">哈哈啊哈</div>
<script>
// 获取根元素
var root = document.documentElement;
var computedStyle = getComputedStyle(root);
var mainBgColor = computedStyle.getPropertyValue('--color');
console.log('mainBgColor', mainBgColor)
setInterval(() => {
  // 设置CSS变量的值
  root.style.setProperty('--color', generateRandomColor());
}, 1000);
// 生成16进制的值
function generateRandomColor() {
  // 生成随机的 R, G, B 分量
  var r = Math.floor(Math.random() * 256);
  var g = Math.floor(Math.random() * 256);
  var b = Math.floor(Math.random() * 256);

  // 将 R, G, B 转换为 16 进制,并确保长度为 2
  var hexR = ('0' + r.toString(16)).slice(-2);
  var hexG = ('0' + g.toString(16)).slice(-2);
  var hexB = ('0' + b.toString(16)).slice(-2);

  // 拼接成完整的 16 进制颜色值
  var hexColor = '#' + hexR + hexG + hexB;

  return hexColor;
}
</script>
</body>
</html>
复制代码

 

 

-

posted @   古墩古墩  Views(259)  Comments(0Edit  收藏  举报
相关博文:
阅读排行:
· 【.NET】调用本地 Deepseek 模型
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· DeepSeek “源神”启动!「GitHub 热点速览」
· 我与微信审核的“相爱相杀”看个人小程序副业
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
历史上的今天:
2021-02-01 判断数组中存在重复元素
点击右上角即可分享
微信分享提示