如何使用 JavaScript(普通或 jQuery)获取和设置 CSS 自定义属性(通过样式表中的 var(…) 访问的属性)?
这是我不成功的尝试:单击按钮会更改通常的 font-weight 属性,但不会更改自定义 --mycolor 属性:
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style>
body {
--mycolor: yellow;
background-color: var(--mycolor);
}
</style>
</head>
<body>
<p>Let's try to make this text bold and the background red.</p>
<button onclick="plain_js()">Plain JS</button>
<button onclick="jQuery_()">jQuery</button>
<script>
function plain_js() {
document.body.style['font-weight'] = 'bold';
document.body.style['--mycolor'] = 'red';
};
function jQuery_() {
$('body').css('font-weight', 'bold');
$('body').css('--mycolor', 'red');
}
</script>
</body>
</html>
Your Answer
2 个回答
原生解决方案
获取/设置 CSS3 变量的标准方法是 .setProperty() 和 .getPropertyValue()。
如果您的变量是全局变量(在 :root 中声明),您可以使用以下内容来获取和设置它们的值。
// setter
document.documentElement.style.setProperty('--myVariable', 'blue');
// getter
document.documentElement.style.getPropertyValue('--myVariable');
但是,如果已使用 .setProperty() 设置了 var 的值,则 getter 只会返回该值。
如果已通过CSS声明设置,将返回undefined。在这个例子中检查一下:
let c = document.documentElement.style.getPropertyValue('--myVariable');
alert('The value of --myVariable is : ' + (c?c:'undefined'));
:root{ --myVariable : red; }
div{ background-color: var(--myVariable); }
<div>Red background set by --myVariable</div>
为了避免这种意外行为,您必须在调用 .getPropertyValue() 之前使用 getCompulatedStyle() 方法。
然后吸气剂将如下所示:
getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');
在我看来,访问CSS变量应该更加简单、快速、直观和自然......
我个人的做法
我实现了 CSSGlobalVariables 一个小型 (以便更轻松地访问和操作.
// get the document CSS global vars let cssVar = new CSSGlobalVariables(); // set a new value to --myVariable cssVar.myVariable = 'red'; // get the value of --myVariable console.log( cssVar.myVariable );
应用于对象属性的任何更改都会自动转换为 CSS 变量。
您可以使用document.body.style.setProperty('--name', value);:
var bodyStyles = window.getComputedStyle(document.body);
var fooBar = bodyStyles.getPropertyValue('--foo-bar'); //get
document.body.style.setProperty('--foo-bar', newValue);//set
Hot Questions
function_exists()无法判定自定义函数
2024-04-29 11:01:01
google 浏览器 手机版显示的怎么实现
2024-04-23 00:22:19
子窗口操作父窗口,输出没反应
2024-04-19 15:37:47
父窗口没有输出
2024-04-18 23:52:34
关于CSS思维导图的课件在哪?
2024-04-16 10:10:18
Hot Tools
vc9-vc14(32+64位)运行库合集(链接在下方)
phpStudy安装所需运行库集合下载
VC9 32位
VC9 32位 phpstudy集成安装环境运行库
php程序员工具箱完整版
程序员工具箱 v1.0 php集成环境
VC11 32位
VC11 32位 phpstudy集成安装环境运行库
SublimeText3汉化版
中文版,非常好用
热门话题
抖音等级价目表1-75
20335
7
20335
7
wifi显示无ip分配
13531
4
13531
4
虚拟手机号接收验证码
11850
4
11850
4
gmail邮箱登陆入口在哪里
8835
17
8835
17
windows安全中心怎么关闭
8420
7
8420
7
热门文章
2025年加密货币市场十大趋势预测:下一个风口在哪里?
2025-11-07
By DDD
Galaxy的观点:山寨币ETF大军即将到来 哪些的前景会光明
2025-11-08
By DDD
铁路12306支付失败订单还在吗_铁路12306支付失败订单处理方法
2025-11-07
By DDD
win10字体安装后在软件里找不到怎么办_win10字体安装与识别方法
2025-11-07
By DDD
解决CSS @media 查询优先级与规则覆盖问题的教程
2025-11-07
By DDD





