如何使用 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>
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号
原生解决方案
获取/设置 CSS3 变量的标准方法是
.setProperty()和.getPropertyValue()。如果您的变量是全局变量(在
:root中声明),您可以使用以下内容来获取和设置它们的值。// setter document.documentElement.style.setProperty('--myVariable', 'blue'); // getter document.documentElement.style.getPropertyValue('--myVariable');但是,如果已使用
.setProperty()设置了 var 的值,则 getter 只会返回该值。 如果已通过CSS声明设置,将返回undefined。在这个例子中检查一下:为了避免这种意外行为,您必须在调用
.getPropertyValue()之前使用getCompulatedStyle()方法。 然后吸气剂将如下所示:getComputedStyle(document.documentElement,null).getPropertyValue('--myVariable');在我看来,访问CSS变量应该更加简单、快速、直观和自然......
我个人的做法
我实现了
CSSGlobalVariables一个小型 (以便更轻松地访问和操作.应用于对象属性的任何更改都会自动转换为 CSS 变量。
可用:https://github.com/colxi/ 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