javascript技巧

关注公众号 jb51net

关闭
首页 > 网络编程 > JavaScript > javascript技巧 > JS获取CSS定义var变量值

JavaScript如何获取CSS中定义var变量值

作者:前端 贾公子

CSS变量是该语言的非常受欢迎的补充,尽管它们非常基础,下面这篇文章主要介绍了JavaScript如何获取CSS中定义var变量值的相关资料,文中通过代码介绍的非常详细,需要的朋友可以参考下

前言

在 JavaScript 中,可以通过 getComputedStyle() 方法结合 getPropertyValue() 来获取 CSS 中定义的变量值。以下是具体的实现方法:

示例代码

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>获取 CSS 变量</title>
  <style>
    :root {
      --main-color: #3498db;
    }
    body {
      background-color: var(--main-color);
    }
  </style>
</head>
<body>
  <script>
    // 获取根元素
    const root = document.documentElement;

    // 获取 CSS 变量值
    const mainColor = getComputedStyle(root).getPropertyValue('--main-color').trim();

    console.log('CSS变量 --main-color 的值是:', mainColor);
  </script>
</body>
</html>

说明

  1. :root 定义变量:CSS 变量通常在 :root 中定义,确保全局可用。
  2. getComputedStyle():用于获取指定元素的所有计算样式。
  3. getPropertyValue():从计算样式中提取指定的 CSS 变量值。
  4. .trim():去除可能存在的多余空格。

通过这种方式,你可以轻松获取并动态使用 CSS 变量的值!

CSS3 :root 选择器

:root选择器用匹配文档的根元素。

设置HTML文档的背景色:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"> 
<title>菜鸟教程(runoob.com)</title> 
<style> 
:root
{
	background:#ff0000;
}
</style>
</head>
<body>

<h1>菜鸟教程</h1>

</body>
</html>

在HTML中根元素始终是HTML元素。

CSSStyleDeclaration getPropertyValue() 方法

getPropertyValue() 方法返回指定的 CSS 属性的值。

object.getPropertyValue(propertyname)
参数描述
propertyname必需。一个字符串,表示要检测的属性名。

返回 color 属性的值:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
<style>
#ex1 {
  color: red !important;
}
</style>
</head>
<body>
<h1>getPropertyValue() 方法</h1>

<p>点击按钮返回 color 属性值。</p>

<button onclick="myFunction()">点我</button>

<div id="ex1">一些文本。</div>

<script>
function myFunction() {
  var declaration = document.styleSheets[0].cssRules[0].style;
  var propvalue = declaration.getPropertyValue("color");
  alert(propvalue);
}
</script>

</body>
</html>

styleSheets

cssRules

定义CSSStyleSheet 对象的属性,返回样式表中所有 CSS 规则 的集合(CSSRuleList 对象)。

包含内容

访问规则

// 获取第一个样式表中的所有 CSS 规则
const rules = document.styleSheets[0].cssRules;

关键特性

属性/方法说明
styleSheets.length文档中样式表的数量
cssRules.length单个样式表中 CSS 规则的数量
cssRules[index]获取具体规则(返回 CSSStyleRule 对象)
rule.style访问规则的样式属性(如 cssRules[0].style.color = "blue"
insertRule()向样式表插入新规则(需指定索引)
deleteRule()删除样式表中的规则

使用示例

// 获取第一个样式表
const styleSheet = document.styleSheets[0];

// 遍历所有 CSS 规则
for (let rule of styleSheet.cssRules) {
  if (rule instanceof CSSStyleRule) { // 过滤普通样式规则
    console.log("选择器:", rule.selectorText);
    console.log("样式:", rule.style.cssText);
  }
}

// 修改第一条规则的背景色
styleSheet.cssRules[0].style.backgroundColor = "yellow";

// 添加新规则
styleSheet.insertRule("body { font-size: 20px; }", 0);

// 删除第一条规则
styleSheet.deleteRule(0);

注意事项

  1. 同源策略限制
    跨域样式表(如 CDN 引入的 CSS)的 cssRules 可能为 null(需 CORS 支持)。

  2. @import 规则
    导入的样式表会作为独立条目出现在 styleSheets 中。

  3. 动态修改
    通过 cssRules 修改的样式会 实时生效,但不会影响原始 CSS 文件。

  4. 规则类型判断
    使用 instanceof 区分规则类型(如 CSSMediaRuleCSSKeyframesRule)。

典型应用场景

通过 document.styleSheets 和 cssRules,开发者能以编程方式深度操作 CSS,实现灵活的样式控制。

Window getComputedStyle() 方法

getComputedStyle() 方法用于获取指定元素的 CSS 样式。

获取的样式是元素在浏览器中最终渲染效果的样式。

window.getComputedStyle(element, pseudoElement)

参数说明:

返回值

返回的对象是 CSSStyleDeclaration 类型的对象。

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</title>
</head>
<body>

<p>点击按钮计算 DIV 的背景颜色。</p>
<p><button onclick="myFunction()">点我</button></p>
<div id="test" style="height: 50px;background-color: rgb(178, 116, 230);">测试 DIV</div>
<p>计算值为: <span id="demo"></span></p>

<script>
function myFunction(){
    var elem = document.getElementById("test");
    var theCSSprop = window.getComputedStyle(elem, null).getPropertyValue("background-color");
    document.getElementById("demo").innerHTML = theCSSprop;
}
</script>

</body>
</html>

Window getComputedStyle() 方法和 style 的异同

getComputedStyle 和 element.style 的相同点就是二者返回的都是 CSSStyleDeclaration 对象,取相应属性值得时候都是采用的 CSS 驼峰式写法,均需要注意 float 属性。

而不同点就是:

我们可以通过使用 getComputedStyle 读取样式,通过 element.style 修改样式。

总结

到此这篇关于JavaScript如何获取CSS中定义var变量值的文章就介绍到这了,更多相关JS获取CSS定义var变量值内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文